CSS Parent Float Fix

Here is a common scenario I’ve seen and been asked about. You have something like a nav, you’re floating the internal elements and for some reason the background you’ve assigned in a parent isn’t extending under these floating elements.

This is a simple example of what I’m talking about. There should be an orange background behind white text.

It’s pretty basic and easy to gloss over what’s happening if you have a fix. I’m going to do a quick scenario to show what’s happening, show why it’s happening and provide a simple fix.

Where is the background?

An easy way to think of this is when you tell an element to float, it and all its children suddenly have no effect on elements around them which is basically what we want. The issue though is the exactly that, in this case the children of nav have dimensions of 0px and since we haven’t explicitly set dimensions on the parent it’s also 0px.

What’s the fix

One simple method is setting a height in the parent, in this case the nav element. The downside though is this isn’t dynamic at all which is a big mistake these days.

What we want to do is do something that will provide the parent with information about the height of the elements it contains without removing their float. While the parent can’t determine the height of its children, an element after those floating elements can use the clear element so to force it under the floating elements. A simple way to do this is to utilize the CSS :after pseudo element and apply a class to the parent. That code would look like this.