Clearing Floats

One of the problems with floating objects is that the float property is then inherited by the other children of the parent element. In practical terms, that means that other elements will wrap to the side of the floated element. Let’s take the page we were just working on in the layout tutorial, and see this in action.

Float a logo

Insert the “occupy.jpg” logo into the header of the sample layout, and put an <h1> tag around the header text.

You’ll see the logo is on top of the text. We want it to appear in the left of the header so the text wraps to the right. We’ll do that by creating a class and applying that to the image:

.floatleft {float:left; margin-right: 15px;}

Now we have a new problem. You can see the nav, sidebar and content areas are wrapping to the right of the image as well.

That is because the image is too tall to contain the float, and it is being inherited. There are two quick solutions to this problem.

The first and easiest, is to simply ensure the parent element of the image has enough height. The image is 163px tall, so if you give the header CSS enough height that will fix the problem.

You can also use what is called the “clearfix hack”. Create a class that looks like this:

.clearfix::after {
content: "";
clear: both;
display: table;}

And then apply this class to the containing element, which is the header.

<header class="clearfix">

Voila, no more inherited float!

Western University: Faculty of Information & Media Studies

Powered by WordPress. Designed by WooThemes