简体   繁体   English

调整父div的大小以匹配绝对位置的子div高度

[英]Resize parent div to match absolutly positioned child div height

I have a CSS problem: 我有一个CSS问题:

I have an absolute positioned div in a container. 我在容器中有一个绝对定位的div。 The container won't resize to the height of the content. 容器不会调整为内容的高度。 Why? 为什么?

You need to use JavaScript for this. 您需要为此使用JavaScript。 With jQuery you can do 使用jQuery,您可以做

var parentHeight = $('#parent').height(),
    childHeight = $('#child').height();

if (parentHeight <= childHeight) {
    $('#parent').height(childHeight);
}

Check working example at http://jsfiddle.net/mkCU5/2/ http://jsfiddle.net/mkCU5/2/中查看工作示例

Because when you give absolute position to something, you take it out of the layout flow. 因为当您为某物赋予absolute位置时,会将其从布局流程中移出。 This means that its dimensions are no longer used to calculate its parent's height, among everything else. 这意味着,除其他外,它的尺寸不再用于计算其父代的高度。

If your element has a known fixed height, then you can give an appropriate height to its parent element as well. 如果您的元素具有已知的固定高度,则也可以为其父元素赋予适当的高度。 Otherwise you should look for another way to achieve your goal. 否则,您应该寻找实现目标的另一种方法。

When something is absolutely positioned with CSS, it takes it out of the flow. 当CSS绝对定位某些东西时,它就将其排除在流程之外。 When it's out of the flow, it won't be accounted for in height calculations. 当它离开流程时,不会在高度计算中予以考虑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM