如何阻止绝对定位元素的父级折叠?
在以下代码中,外部div的高度为0:
<div id="outer" style="position: relative;">
<div id="inner" style="position: absolute; height: 100px;">
<p>This is the inner content.</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这与这个问题非常相似,你如何保持浮动元素的父母不会崩溃?,它处理浮动元素,但我尝试了一些解决方案(包括spacer和clearfix类),但它们不起作用.
谢谢!
小智 4
你不能:一旦子进程处于绝对位置,它实际上就在父进程的“外部”(从外观上看)。
如果你已经包含了 jquery,你能做的就是使用这个不优雅的 hack :
$(".absolutepos").each(function() {
$(this).parent().css("height",$(this).height());
});
Run Code Online (Sandbox Code Playgroud)
并在将 div 置于绝对位置时添加“absolutepos”类:
<div id="outer" style="position: relative;">
<div id="inner absolutepos" style="position: absolute; height: 100px;">
<p>This is the inner content.</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)