How to Use CSS Float and Clear Properties

Programmers

floatandclearIf you’ve ever been confused by the myriad of choices when it comes to CSS’s display,float, and clear properties, this post is for you. And let’s be honest, we’ve all been there. Hopefully, though, by the end, you’ll be able to confidently choose what to use and why.

Float

The CSS float property was one of the first properties I learned. There are only 4 options: Left, Right, None, or Inherit. On the surface, these seem pretty basic.

Floating left will make the Div “float” to the left, allowing another Div (that’s also got the float:left property) to be beside it.

Floating right does the opposite thing, with the first Div on the far right.

Inherit means whatever the parent Div’s property is, that’s what their property will have.

Finally, the none property is default, but you can also specify it.

So nothing ground-breakingly crazy there. The big thing is how the float property interacts with the clear property. I’ve included a jsFiddle below for you to see exactly what happens.

Clear

The clear property is a bit more tricky. It has 5 options: Left, Right, Both, None, Inherit. The tricky part, though, is in what exactly it does.

For the longest time, I didn’t actually understand this property. It never worked like I expected it to. Here’s how it actually works (and you can test it out in the jsfiddle below):

The clear property will effect whatever Div it’s on. So if you were narrating what’s going on, you would say “This Div should float right, and will start with nothing to the left of it” (clear: left). It DOES NOT mean “This Div will float right and nothing AFTER it will float to the right. Confused? Yeah, well it’s a big club. We should get t-shirts.

The clear property effects the Div it’s property is added to, not the Divs following it.

Fixing the Float Property with the Clear Property

You may have noticed in your past experience or the jsFiddle above an important issue with Float and Clear: Any Div that these are placed into (parent Divs) do not automatically expand. This is a HUGE issue! But don’t worry, the solutions are easy.

Solution 1. Use a clear:both on a Div at the very bottom. Notice on the bottom Div above we added a clear:both, but no Float property. If you add the Float property it will negate the clear property.

Solution 2. Add overflow:auto to the parent Div. I personally like this solution better because you aren’t dependent on that last Div to make everything work. Now this isn’t a fix-all; there are some tricky things about this one as well, such as whether the height is set, scrollbars, etc, but generally speaking, it’s a nice easy way to fix this issue.

Comments