Question

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

  • Keep the HTML markup as semantic and free of unnecessary elements as possible, and
  • Be a cross-browser, cross-platform solution that works reliably for the majority of browsers?
Était-ce utile?

La solution

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.

Autres conseils

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.

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/

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

.wrapper::after {
    content:"";
    clear:both;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top