How can I use “float: left” in a div without breaking the containing element's height?

前端 未结 6 2080
借酒劲吻你
借酒劲吻你 2020-12-10 18:49

It seems that floated HTML elements don\'t expand the heights of their containers. For example, consider the following code:

6条回答
  •  离开以前
    2020-12-10 19:00

    I would highly recommend NOT to use hacks like ClearFix. If you're trying to save a

    because it's not "semantic" you're going to set yourself up trouble down the line. Best, if you know your layout won't change, or you can tell for sure what the next element is, you can use the next element to clear previous "floats". If you need something modular, like a piece of HTML that can be inserted in various places, then always add the clearing DIV.

    Also regarding David's comment:

    Be careful as that is not valid HTML or XHTML. Although it seems valid from a XML point of view, it does not respect the document definition (whatever it's called, which is referred to by the DOCTYPE tag). In other words, the DIV is defined as an element that opens, and closes with a separate closing tag. Contrary to a
    for example, which allows for "self-closing". Granted, Firebug and possibly other web developer tools, will sometimes show DIVs that way but that's just how they display it.

    PPS: at my job I've found that this worked well in some layouts to fix inconsistent vertical spacing between elements when clearing DIVs in IE6 and other browsers:

    Cross browser clearing:

    div.clear { clear:both; overflow:hidden; height:0; }
    
    

    Don't use an inline style for this, ever. First you will need it often, and second, as yo ucan see above, it may come in handy to change the clear rule to fix some cross browser troubles.

提交回复
热议问题