开发者

What is the meaning of an otherwise empty <div> with the CSS clear:both property?

I'm wondering if anybody knows the meaning of this tag I found in a valid html file开发者_开发问答 I've downloaded.

<div style="clear: both;">&nbsp;</div>

Thanks for help in advance.


It clears the floats from both left and right in order to bring the content after it back into the main flow of the page.

Official definition.


The technique is known as a "spacer div" - the article is now ten years old and at the time this was a good solution to a common problem. It typically appears in scenarios like this:

<div class="container">
  <div style="float:left">
    ...
  <div style="float:left">
    ...
  </div>
  <div style="clear:both">&nbsp;</div>
</div>

The inner divs are floated - if you simply left out the "spacer div" the container element would not completely enclose its contents (unless you float it itself, which is often impractical). The &nbsp; is needed in some older browsers (you know which one) to ensure it behaves as expected in all situations, i.e. a simple <div style="clear:both"/> didn't always work - you really needed a div with actual (though invisible and nonsensical) content to make it work everywhere.

It's a working solution to a common problem, but there are more elegant ways to solve this, e.g. using the :after CSS pseudo class. This is more elegant because it doesn't require us adding semantically worthless markup elements that are just there for styling purposes. Another great article with a different solution.


This tag will not allow any float to be place either left or right of this tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜