CSS Floats Made Easy
We see the images in newspaper and articles are placed in certain position with rest of the content wrapped around it. But how is this possible because by default, block-level elements will not line up beside one another in a column-based format. Since columns are necessary in virtually every CSS layout, the float property is used to get this look.
What is a “Float” ?
The CSS float property allows a developer to incorporate table-like columns in an HTML layout. Float property forces any element to float inside its parent body with the rest of the element to wrap around it.
As I mentioned, originally Floats by design were created to allow flowing text around an image. Floats were not meant for layouts! If you try to use float property for full web page layout, making the page fully responsive will be a real struggle.
Now that we understand the intended purpose of floats, lets learn some tips and tricks that will helpful when working with floats.
Syntax:
float: left | right| none | inherit ;
Tips and Tricks
– If you are floating the child elements make sure you clearfix the parent element otherwise the parent element may collapse.
<div class="parent clearfix"></div>.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: "";
clear: both;
height: 0;
}
– You need to clear the floats (left or right) from immediate next sibling of the floated elements otherwise these opportunist guys will try to take the place of the elements that were floated.
.sibling {
clear: both;
}
– All the other properties like padding and margin can be easily applied to the floated elements, provided the elements are created semantically and enclosed in <div>.
– For creating a simple nav its better option to float the <li> elements rather than using display: inline block; as the later will create a stubborn whitespace things which can be tricky to get rid of.
– Some of really interesting layouts can be created with using float: right; much less used contemporary of float: left;
– When you apply a float to an element, it no longer behaves as a block level element. Instead, its width becomes the size of its contents unless otherwise specified.
– An element floating up out of the natural page flow and other elements taking its place means that the stacking order of the HTML elements (the way they appear on the page) changes. This change is more dramatic when float property is used with right as its value.
Conclusion
The concept was not easy to get hold of when I first started using floats. I remember the day when I learned Flexbox and felt so much relieved that I will never have to use floats for laying out my web pages. But this happiness was not long lived when I realized that if you are in front end web development industry, you cannot escape floats. You may come across code were floats are used for layouts for a section of a page if not for the whole page layout.