In the previous blog, we just have an interesting talk about css display. We have learned how to define page layout by using css display. Today, we will take about one more property which is also related to web layout that is css property
float
.
What is
float
According to Mozilla document: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Floats . Originally float was introduced in order to let an element is able to float inside a column of text. The kind of thing you might get in a newspaper layout like this:

Live demo: comparison between
display:inline-block
vs
float: left
See the Pen float cs display by hieu (@phuchieuct93abc) on CodePen.
However, software developers are much more smart and creative than we can image, they quickly realized that they can float every element(not only for image and text) and use float for create the entire web layout. Bootstrap 3 is a popular example. They used
float:left
in their grid system layout. Nowadays, the word has changed, there are more proper technique help us to create web layout easily such as
display:flex
and
grid
. Bootstrap 4 also shifted their implementation from heavily depend on
float
to
flex
. Therefor, float comes back to their original responsibility which is defined image float on the text.
Keep in mind that when you have
float
in your CSS code is that you need to take some precaution to make the surrounding element to encompass the floated elements, and also to avoid following elements in the code to sneak up next to it.
In case you’re not ready to switch to
flex
or
grid
and you want to solve your current problems which related to
display:inline-block
, you can still able to use
float
. The following examples will show you when to use
float
to solve that kind of problem.
Problem : space between inline elements
By default, browsers will render an extra space between
inline-block
elements. It is not the bug, it’s a feature like the space between the words. In some case, you want to remove that space but you’re not successful despite of how much you tried to remove that space. With the help from
float
, you can easily remove that margin, make them sit next together.
See the Pen CSS display: inline-block by hieu (@phuchieuct93abc) on CodePen.
Wrap up
Please keep in mind that avoid using
float
to defined the layout as much as possible, that is not the original purpose of
float
. Instead using
flex
or
grid
is much better and healthy. Only use
float
when you actually want to make something
float
on others. Hope you learned some thing and see you in the next post.