gpt4 book ai didi

javascript - 如何将容器 div 的大小调整为其子级的总高度?

转载 作者:行者123 更新时间:2023-12-03 21:49:50 26 4
gpt4 key购买 nike

我有一个容器元素,需要随着其内容的变化而调整其大小。它包含 2 个绝对定位的 div,它们都可以改变高度。如果我不指定容器的高度,那么容器后面的任何内容都会消失在内容下。

目前我正在执行以下操作,但我很高兴找到一个不那么费力的替代方案:

(容器的position:relative,#main和#sidebar的position:absolute,#sidebar的内容没有指定定位)

CSS:

div#mapcontainer { position:relative; width:100%; height: 600px;  }
div#main { position:absolute; top: 0; left: 10px; width: 500px; height: 400px; }
div#sidebar { position:absolute; top:10px; right:10px; width: 155px; height: 405px;}

html:

<div id="container">
<div id="main">variable height content here</div>
<div id="sidebar">
<div id="foo">...</div>
<div id="bar">....</div>
...
</div>
<div>

js:

fixHeights = function() {   
var children_height = 0;
$('#sidebar'). children().each(function(){children_height += $(this).height();});
$('#container').height(Math.max(children_height, $('#main').height()));
};

最佳答案

这是一个非常奇怪的问题,因为 div 的高度始终是其子级的高度。

您的容器 div 中是否有 float 内容?当您 float 子内容时,包含的 div 的行为不再相同。

如果您的 float 内容超出了容器 div 的底部,请将以下 div 添加到容器 div 的子级的最底部:

<div style="clear:both;"></div>

这将不允许子元素漂浮在其上方,从而强制包含的 div 为其最高子元素的高度...

<div id="container">
<div id="dynamic" style="float:left;width:100px;">dynamic content goes here</div>
<div id="static" style="margin-left:104px;">Lots of static stuff here</div>
<div style="clear:both;"></div>
</div>
<小时/>

好吧,我不知道你为什么要这样做定位,但我已经为一个必须看起来像桌面应用程序的网站做了类似的事情。我不相信除了使用 javascript 之外还有其他方法可以做到这一点。 Html 文档的设计是流畅的,而不是死板的。如果您想放弃 JavaScript,则必须放弃定位样式并使用 float 和清除 div。没那么可怕...

关于javascript - 如何将容器 div 的大小调整为其子级的总高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/317472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com