10

Can anyone tell me why do the block level elements given float property does behave oddly? I want to understand what actually happens to an element[block or inline] when we give a float property.

Below is the code and fiddle:

<div class="container violet">
  <div class="float red">float</div>
  <div class="foo blue">foo</div>
  <div class="bar green">bar</div>
  <div class="baz orange">baz</div>
</div>

CSS

.float {
  float: left;
}
.foo {
  padding-top: 10px;
}
.bar {
  width: 30%;
}
.baz {
  width: 40%;
}

.violet{
  background-color: violet;
}
.red{
  background-color: red;
}
.blue{
  background-color: blue;
}  
.green{
  background-color: green;
}
.orange{
  background-color: orange;
}

http://jsfiddle.net/gcazev14/

My curosity, it is still in the normal flow but its now positioned inside the foo[blue] block

ShankarGuru
  • 627
  • 1
  • 6
  • 17
  • Float elements do not take any space in the dom, except for their specific contents, or specific size / width that you assign to them. Even so, you will find that sibling elements will "stretch" such that the left of the sibling ("foo" in your fiddle) is all the way to the left of the floated element ("float" in your fiddle) – random_user_name Dec 10 '15 at 00:20

2 Answers2

15

It is because the original intended purpose of floats was not to put block elements side by side, but to reproduce the traditional typographical effect of wrapping text around images and boxouts as seen in this diagram from the CSS 2 spec.

Floats

There are various workarounds, but you'd probably be better off with display: inline-block, flexbox or CSS grids if you want side-by-side blocks.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

When you float an element it takes it out of the normal flow. If you inspect it's parent without any other siblings, the parent element will not have a height. The floated element actually punches through the bottom of its parent.

Floating an element also makes its width collapse to the width of its content (if any). That means, if it has no content, it'll be 0 width. So, if you want it to have a certain width, you have to set that.

If you want the parent to contain it, you'll either need a sibling element to clear the float with "clear: both" or you'll need to do something like bootstrap does with ".clearfix" (Understanding Bootstrap's clearfix class)

Depending on how you want the floated element’s siblings to interact with it, you may also need to float them.

Community
  • 1
  • 1