问题:
Although elements like <div>
s normally grow to fit their contents, using the float
property can cause a startling problem for CSS newbies: If floated elements have non-floated parent elements, the parent will collapse. 尽管<div>
的元素通常会增长以适应其内容,但是使用float
属性可能会给 CSS新手带来一个惊人的问题: 如果 float
元素具有非 float
父元素,则父元素会折叠。
For example: 例如:
<div> <div style="float: left;">Div 1</div> <div style="float: left;">Div 2</div> </div>
The parent div in this example will not expand to contain its floated children - it will appear to have height: 0
. 在此示例中,父div 不会扩展为包含其浮动子级-它将看起来具有height: 0
。
How do you solve this problem? 你怎么解决这个问题?
I would like to create an exhaustive list of solutions here. 我想在这里创建一个详尽的解决方案列表。 If you're aware of cross-browser compatibility issues, please point them out. 如果您知道跨浏览器的兼容性问题,请指出。
Solution 1 解决方案1
Float the parent. 浮动父母。
<div style="float: left;"> <div style="float: left;">Div 1</div> <div style="float: left;">Div 2</div> </div>
Pros : Semantic code. 优点 :语义代码。
Cons : You may not always want the parent floated. 缺点 :您可能并不总是希望父母浮动。 Even if you do, do you float the parents' parent, and so on? 即使您这样做,您是否也浮动了父母的父母,依此类推? Must you float every ancestor element? 您是否必须浮动每个祖先元素?
Solution 2 解决方案2
Give the parent an explicit height. 给父母明确的身高。
<div style="height: 300px;"> <div style="float: left;">Div 1</div> <div style="float: left;">Div 2</div> </div>
Pros : Semantic code. 优点 :语义代码。
Cons : Not flexible - if the content changes or the browser is resized, the layout will break. 缺点 :不灵活-如果内容更改或浏览器调整大小,布局将中断。
Solution 3 解决方案3
Append a "spacer" element inside the parent element, like this: 在父元素内附加一个“ spacer”元素,如下所示:
<div> <div style="float: left;">Div 1</div> <div style="float: left;">Div 2</div> <div class="spacer" style="clear: both;"></div> </div>
Pros : Straightforward to code. 优点 :直接编写代码。
Cons : Not semantic; 缺点 :没有语义; the spacer div exists only as a layout hack. spacer div仅作为版式hack存在。
Solution 4 解决方案4
Set parent to overflow: auto
. 将父级设置为overflow: auto
。
<div style="overflow: auto;"> <div style="float: left;">Div 1</div> <div style="float: left;">Div 2</div> </div>
Pros : Doesn't require extra div. 优点 :不需要额外的div。
Cons : Seems like a hack - that's not the overflow
property's stated purpose. 缺点 :好像是hack-这不是overflow
属性的既定目的。
Comments? 评论? Other suggestions? 还有其他建议吗?
解决方案:
参考一: https://stackoom.com/question/uuO/您如何防止浮动元素的父项崩溃-重复参考二: https://oldbug.net/q/uuO/How-do-you-keep-parents-of-floated-elements-from-collapsing-duplicate
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4315727