0

I can understand this code.

.container {
  border: 2px solid black;
}

.float {
  border: 2px solid red;
  float: left;
}
<!DOCTYPE html>
<html>

<body>

  <div class="container">

    <div class="float">i am float</div>

  </div>

</body>

</html>

But when overflow hidden is applied to container element why does not floated element gets hidden like it should according to description of overflow:hidden;. Rather the container element wraps itself around floated element. Cam u explain this ?

.container {
  border: 2px solid black;
  overflow: hidden;
}

.float {
  border: 2px solid red;
  float: left;
}
<!DOCTYPE html>
<html>

<body>

  <div class="container">

    <div class="float">i am float</div>

  </div>


</body>

</html>

2 Answers2

3

Declaring overflow any value other than visible will establish a new block formatting context, which makes the div contains its children. You could also declare position: absolute to achieve the same "clearing" effect like this.

.container {
  border: 2px solid black;
  overflow: hidden;
}

.float {
  border: 2px solid red;
  float: left;
  position: absolute;
}
  <div class="container">
    <div class="float">i am float</div>
</div>

Refer here for more info about how an element's height is determined by default

For more info refer here

theWellHopeErr
  • 1,856
  • 7
  • 22
1

This is because your container does not have any width or height constraints so it will grow with whatever is inside of it. Take at look at this, I've added height: 10px to the container CSS and look what happens when overflow is hidden and when its visible:

Hidden:

.container {
  border: 2px solid black;
  height: 10px;
  overflow: hidden;
}

.float {
  border: 2px solid red;
  float: left;
}
<body>
  <div class="container">
    <div class="float">i am float</div>
  </div>
</body>
</html>

Visible:

.container {
  border: 2px solid black;
  height: 10px;

}

.float {
  border: 2px solid red;
  float: left;
}
<body>
  <div class="container">
    <div class="float">i am float</div>
  </div>
</body>
</html>
John
  • 5,132
  • 1
  • 6
  • 17