0

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?
jmlane
  • 2,109
  • 1
  • 16
  • 24

4 Answers4

3

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.

DA.
  • 39,848
  • 49
  • 150
  • 213
  • Thanks. This method seems to be the favoured solution from other research I've done since posting the question. – jmlane Jan 04 '12 at 19:31
1

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.

Benny Andajetz
  • 123
  • 1
  • 4
  • Sorry, the tag didn't format and show correctly. Put this as the next div:
    – Benny Andajetz Nov 02 '11 at 16:47
  • @DA. is correct, the additional (likely semantically unnecessary) markup from the clearfix solution violates my first criterion. A valid answer, but I'd like to see if anyone proposes a solution that doesn't require additional markup. – jmlane Nov 07 '11 at 05:54
  • My reasoning behind doing it this way: It is a compromise because it isn't semantic. But it works cross-browser and backwards without jumping through any hoops. I understand the distaste for it, though. – Benny Andajetz Nov 08 '11 at 18:55
0

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

.wrapper::after {
    content:"";
    clear:both;
}
chown
  • 51,908
  • 16
  • 134
  • 170
0

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/

imsoper
  • 11
  • 4