why do we loose parent styles when we use floats in css

I know float is no more used and is replaced by flex, but just curious to know why does it loose parent styles when implemented .

Example :

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flex</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="one">
            <h1>Section 1</h1>
        </div>
        <div class="two">
            <h1>Section 2</h1>
        </div>
        <div class="three">
            <h1>Section 3</h1>
        </div>
    </div>
</body>
</html>

style.css

body{
    margin: 0;
}
h1{
    margin: 0;
}


.container {
    background-color: tan;
}

.one, .two, .three {
    float: left;
    width: 300px;
    height: 200px;
    text-align: center;
    padding: 7px;
    background-color: thistle;
    border: 1px solid slategrey;
}

In the above example the background color of container div doesnt work anymore after float is implemented !

 

Answer

That's because elements that you have assigned 'display: float' to are now floating. They are taken outside of the normal document flow.

If you still want to use float you'll need to use clear.

h1 {
  margin: 0;
}

.container {
  background-color: tan;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

.one,
.two,
.three {
  float: left;
  width: 300px;
  height: 200px;
  text-align: center;
  padding: 7px;
  background-color: thistle;
  border: 1px solid slategrey;
}
<div class="container clearfix">
  <div class="one">
    <h1>Section 1</h1>
  </div>
  <div class="two">
    <h1>Section 2</h1>
  </div>
  <div class="three">
    <h1>Section 3</h1>
  </div>
</div>