Why does not <div style={{ backgroundColor: "black" }}></div> render black but <div style={{ backgroundColor: "black" }}> Hello </div> doesn't?

I am trying to learn React.JS and something kind of blew my mind.

I have this Header component :

class Header extends Component {
  render() {
    return <div style={{ backgroundColor: "black" }} />;
  }
}

that I am calling in my App.js :

function App() {
  return <Header />;
}

When the code stays like this, nothing shows on my web page. But if I change my Header component to this :

class Header extends Component {
      render() {
        return <div style={{ backgroundColor: "black" }}> Hi</div>;
      }
    }

I get a black line on the top of my web page.

I don’t understand why writing something into my div makes me get the blackline, and I was wondering how can I get the black background without writing anything in my ?

3 thoughts on “Why does not <div style={{ backgroundColor: "black" }}></div> render black but <div style={{ backgroundColor: "black" }}> Hello </div> doesn't?”

  1. There are a couple of reasons for this:

    1. div is not a self-closing tag, i.e. you can’t use it like <div /> and instead it must be used as <div></div>
    2. An empty div has no height so there is nothing to add background colour to.

    To fix this you must

    1. Add a style to the div which specifies the height e.g. height: "32px"
    2. To see the text, you must change the color of the text so it is visible e.g. color: "white", backgroundColor: "black"
    return <div style={{ height: "32px", color: "white", backgroundColor: "black" }}> Hi</div>;
    
    Reply
  2. Your header doesn’t have a height so in the case that it has no text it is a height of 0px so you don’t see the background color, if you add text to the header it stretches to accommodate the text so it gets a height automatically and that is why you see the back background.

    If you want to have an empty header with a black background try editing your code as mentioned by @Kayden van Rijn like this style={{ backgroundColor: "black", height: "32px" }}

    Reply

Leave a Comment