Ben Fairbanks

Freelance Website Developer

Floats Fear Them, Face Them, Make Them Your Own

Feb 25, 2017

Many baby coders who attempt to tinker with the dark art know as float come away burned. The position sisters make some sense, (Static, Absolute and Relative) but trying to use float without a decent understanding of what effects it has and how to use it to accomplish your goals tends to end in a train wreck. To get this understanding of why floats work the way that they do and what their inherent limitations are it helps to have some (semi)historical context. Floats were thought up in the early days of the modern Internet, as a way to make images and text align nicely for newspaper websites. Before floats html was pretty static, with everything element listed one after the other.

An ugly Pizza Hut website

This was not the most intuitive way for a website to be constructed, and quite frankly it was pretty ugly. It was all we knew back then, but some small part of us screamed that there must be something better. Thus the impetus for the float was born, and the creation of the classic chunk of words next to a picture layout was born.

A happily floated New York Times Article

So how was this achieved? Floats work in a very different way than absolute or relative positioning. Floats, rather than targeting themselves and achieving the desired page space through moment actually affect the parent element of the child it is called upon. This is important, and seems counterintuitive, so I will say it again: Floats affect the parent element of the element they are called on, rather than inherently changing the child element. With that out of the way floats accomplish their task by setting the hight of the parent element to zero, crumpling and collapsing it so that every element is on the same point on the y axis.

This must be a complicated process to achieve, in terms of code? Not in the slightest. In your CSS file, simply assign float: left or float: right on the element you desire it to be called upon. Thats it. Float left sends it to the left of the page and pulls everything below it up to the same point on the axis to the right of it, with elements wrapping around the floated element if necessary, and float right accomplishes the chiral.

But wait you are saying, doesn't this leave everything a crumpled mess? Why yes. Yes it does. Getting only this far with understanding floats is normally the problem, as it leaves the code mangled and the coder flustered. The solution is clear; clear: left|right|both to be precise. Clear restores the height of the parent element at its location and after, it's essentially a float dam. The time honored way of calling float is to create an empty span element and then calling clear on it in the css.

With these two tools you can implement float in your website, creating a more visually appealing layout that will please you and anyone you show it to. Good luck!

Share this on Twitter!