css - float 溢出和位置冲突

标签 css

我有一个溢出的 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(因为 #fatherposition: 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 or overflow: hidden; on the #son element.

关于css - float 溢出和位置冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11158841/

相关文章:

javascript - img.src 属性是否必要?

css - 容器固定宽度。中心 div 动态宽度。想要左右div平均填充剩余宽度

jquery - 有没有办法像 IE 一样在 firefox 中将 alt ="text"显示为鼠标悬停工具提示?

html - 在不使用框架的情况下使用菜单构建网站

html - 使用 Jquery 的滚动菜单

html - 将元素放在 div 的中心

javascript - 如何使 bootstrap nav-pills 在点击时关闭?

css - Bootstrap 3 - 删除装订线

html - 使用 CSS 灵活盒模型,您可以将 "float"一个元素移至左侧,同时将第二个元素居中吗?

html - 图像未使用 css 从我的系统加载