0

I want my div tags to have different background color than body background color but my browser only shows first div color changed not second one. why?

body {
  background-color: Linen;
}

.names {
  background-color: Yellow;
}

.title {
  background-color: rgb(255, 0, 0)
}
<!doctype html>
<html>

<head>
  <title>Our Blog</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

  <div class="title">
    <h1 align="center">O</h1>
  </div>

  <div class="names">
    <h2 style="float: left">M</h2>
    <h2 style="float: right">F</h2>
  </div>

</body>

</html>

But output is showing just first div background-color change not the second one

deceze
  • 510,633
  • 85
  • 743
  • 889
Roohullah Kazmi
  • 337
  • 3
  • 14

1 Answers1

2

It's not that the names container has no background colour, it's that it has no height:

.names {
  background-color: Yellow;
  border: solid 1px green;
}
<!doctype html>
<html>

<body>

  <div class="names">
    <h2 style="float: left">M</h2>
    <h2 style="float: right">F</h2>
  </div>

</body>

</html>

It only has floated children, and they don't contribute to the height of the parent. Unless you explicitly do something, like telling the parent to prevent overflow:

.names {
  background-color: Yellow;
  overflow: hidden;
}
<!doctype html>
<html>

<body>

  <div class="names">
    <h2 style="float: left">M</h2>
    <h2 style="float: right">F</h2>
  </div>

</body>

</html>
deceze
  • 510,633
  • 85
  • 743
  • 889