jmlane
jmlane

Reputation: 2198

What is the best way to clear floated elements in CSS?

What is currently considered the best way to clear CSS floated elements that will:

Upvotes: 0

Views: 177

Answers (4)

ardianzzz
ardianzzz

Reputation:

a little tricky, but it's work for modern browser :)

.wrapper::after {
    content:"";
    clear:both;
}

Upvotes: 0

imsoper
imsoper

Reputation: 11

The best method I've seen for this is using :before & :after pseudo elements for modern browsers and zoom: 1 for older versions of IE.

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}

More info here: http://nicolasgallagher.com/micro-clearfix-hack/

Upvotes: 0

Benny Andajetz
Benny Andajetz

Reputation: 123

You can make this more complicated, but a simple way is to add a class to your CSS called .clearfix with this attribute:

.clearfix {clear: both;}

Then just insert a tag underneath what you want to clear.

Google clearfix for more modern ways to define the tag.

Upvotes: 1

DA.
DA.

Reputation: 40673

This isn't a graphic design question. It's a CSS one, so belongs on StackOverflow.

That said, the answer for keeping the HTML clean is simply to give the parent an overflow. So if your markup is:

<div class="wrapper">
    <div style="float: left;"></div>
    <div style="float: left;"></div>
</div>

you can give wrapper an overflow:

.wrapper {overflow: auto}

And now .wrapper will contain both the floats.

That's usually all that is needed.

Sometimes, in older IEs, the container also needs a width.

Upvotes: 3

Related Questions