0

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:

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;
}
<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>

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

NearHuscarl
  • 38,825
  • 11
  • 144
  • 140
neeraj tk
  • 2,024
  • 1
  • 9
  • 19

1 Answers1

2

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>

But it's not recommended to use float for designing layout. You can read more about it here: What is a clearfix?.

Magiczne
  • 1,540
  • 2
  • 13
  • 21