我有一个溢出的 float 问题(JSFiddle here)。
HTML
<div id="father">
<div id="son">
gruik
</div>
<div id="dog">
gruikgruik gruik gruik gruikg ruik gruik gruikgr uikgruik gruik gruik gruik
</div>
</div>
CSS
div { border: solid; }
#father { width: 300px; position: relative; }
#father:after { content: ""; display: block; clear: both; }
#son { width: 100px; float: left; border: solid red; }
#dog { float: left; border: solid blue; position: absolute; left: 105px; }
如您所见,#dog
从 #father
溢出。我尝试了经典的 CSS 技术,但它们根本不起作用(无论是 clearfix 方法,还是 overflow:hidden;
或 overflow:auto;
)。
我认为问题的出现是因为使用了位置 CSS 属性,但我需要它。
最佳答案
position: absolute;
正确定位 #dog
元素相对于 #father
(因为 #father
有 position: relative;
).
然而,只有 #son
元素为 #father
提供了它的高度。绝对定位的元素从流中取出,因此如果 #dog
增加高度,其父容器(#father
)不会增加,因此 #dog
看起来溢出了。
为什么必须在 #dog
上使用 position: absolute;
?
你不能只使用 float 并设置它的宽度吗?无论如何你都在设置它的父级和兄弟级的宽度所以你知道它应该是什么宽度(如果你也指定了边框的宽度) .
演示: http://jsfiddle.net/sgw4K/5/
编辑/更新:在发现额外的样式后,thirtydot 推荐了两个声音解决方案来解决这个问题。请参阅下面的评论或以下内容:
To fix that, you can remove
float: left
from#son
and then pick one of these two choices:margin-left: 52px
oroverflow: hidden;
on the#son
element.
关于css - float 溢出和位置冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11158841/