Understanding
CSS Float
Intro
-
One of the main tools for layouting (post tables and pre flexbox)
-
Tables are hard to write and maintain. There’s a performance penalty (flickering white page)
-
Flexbox is becoming more mainstream
-
CSS grid is still relatively new
-
Understanding float will make you a calmer, happier person :)
Basic rules
-
floating an element will cause it to "float" to the side, until it reaches the container or hits another floated element.
-
making an element “float” takes the element out of normal page flow. the element is no longer inline or block. it is "float" (behaves similar to inline-block)
-
the size of the element is determined by its content
Basic rules - cont.
-
a floated element will wrap if there is no room for it (width wise) in the container
-
block elements after the floated element will act as if the floated element is not there
-
inline elements will wrap around it
Weird stuff...
-
the height of a container containing float elements ignores the floated elements
-
inline elements inside block elements coming after floats will wrap around the floats even though the block element ignores the float
-
a float (for instance, left) coming *after* inline text will appear on the left side and the last line of the text, to the right of it (??)
-
Non float box containing text after float boxes
-
Different height float blocks will wrap unexpectedly
Fixing the container collapse
-
Overflow
overflow:hidden or overflow:auto
Have the risk of showing scrollbars or hiding content
Problematic if the container has a height or max-height
Floating the container
clear:both/left/right
Clearing
-
clearing means that an element coming after floats will "see" them and take its place *after* them.
-
this has the effect of fixing the container height to take into account the height of the floats
-
clear:left/right means "see left/right floated elements" clear:both means see both
- most of the times we want to clear a container containing floats *right before* the closing tag of the container
Clearfix
// uses :after to create an empty block element that is cleared at the end of a container
.clearfix:after {
content:"";
display:block;
clear:both;
}
<div class="clearfix">
<div style="float:right"></div>
<div style="float:right"></div>
<div style="float:right"></div>
<div style="float:right"></div>
</div>
CSS float
By Netcraft
CSS float
- 568