hr clear vs div clear. Which is better?

前端 未结 4 912
栀梦
栀梦 2021-01-20 18:18

This is a general question and something that dawned on me and seemed to make sense. I have seen many people use clearing divs

and
4条回答
  •  误落风尘
    2021-01-20 19:03

    According to the HTML5 spec, the hr element represents a paragraph-level thematic break (a scene change in a story, or a transition to another topic within a section of a reference book) while the div element is a generic container for flow content that by itself does not represent anything. So I don't see any justification for choosing one over the other for containing floats.

    However, there's something you should keep in mind. Read the following excerpt from Eric Meyer's article Containing Floats:

    div.item {border: 1px solid; padding: 5px;}
    div.item img {float: left; margin: 5px;}
    div.item hr {display: block; clear: left; margin: -0.66em 0;
        visibility: hidden;}
    

    That's not right Using a horizontal rule to force expansion

    The negative top and bottom margins have the general effect of closing up the space that the hr occupies. However, this effect is not precise, and not necessarily identical across browsers. The semi-mysterious nature of horizontal rules makes it difficult to predict exactly what will happen. The effective height of the hr might be zero, or a small positive amount, or even a negative height

    Therefore, in situations where a precise clearing effect is needed, authors can use a div instead of an hr to create a clearing effect.

    If this didn't make sense to you, see this fiddle and notice the space below the floated div (IE8).

    That said, there are other ways to contain floats and avoid using structural hacks at the same time:

    1. Float the container: may cause layout problems.
    2. Use .container { overflow: auto; }: If the content exceeds the boundaries of the container, you will see a scrollbar.
    3. Use .container { overflow: hidden; }: If the content exceeds the boundaries of the container, it will be hidden.
    4. Clearfix: To be used when 2 and 3 fail.

提交回复
热议问题