user3519495 user3519495 - 3 months ago 8
CSS Question

Confusion about CSS Floats

I'm little confused about floats.
I have created an example for float.
http://jsbin.com/pasavifego/edit?html,css,js,output

I have given a back ground color for my ul as red.

All my li's are floating left, I dont see any background color now. If i remove the float it is working. Can someone explain why this happens.

Another questions is, When one div is float:left,when i add another div, why does it start next to that div.

Can some one please explain this.

Thanks

Answer

@adam-buchanan-smith's answer is a good way of doing this without floats.

But to answer your question, what's happened is the <ul> has no height. As @j08691's comment says, floated elements take up no vertical space in their container. In this example, the second <ul> just shows up as a red line:

ul {
  outline: 1px solid red
}
.with-floated-lis li {
  float: left
}
<ul>
  <li>not floated</li>
</ul>

<ul class="with-floated-lis">
  <li>floated</li>
<ul>
  

The trick to get around this is called the "clearfix hack", and it's an essential tool in frontend development. When you float something and want its container to expand vertically to contain the floated element, apply the clearfix to the container:

.clearfix:before,
.clearfix:after {
  content: " ";
  display: table;
}
.clearfix:after {
  clear: both;
}
ul {
  outline: 1px solid red
}
.with-floated-lis li {
  float: left
}
<ul class="with-floated-lis clearfix">
  <li>floated, ul has clearfix</li>
</ul>

Nicolas Gallagher wrote that clearfix. His post is here http://nicolasgallagher.com/micro-clearfix-hack/. Read more about clearfix and floats here https://css-tricks.com/snippets/css/clear-fix/