gpt4 book ai didi

HTML div 元素不采用其父级的高度,即使父级具有非零高度

转载 作者:太空狗 更新时间:2023-10-29 15:24:58 24 4
gpt4 key购买 nike

我有一个相当简单的问题。我有一个包含三个 child 的容器 div - 两个 div 和一张 table 。以下是 CSS:

#container {
overflow: auto;
}
#child1 {
float: left;
width: 50px;
height: 100%;
}
#table1 {
float: left;
}
#child2 {
float: left;
width: 50px;
height: 100%;
}

HTML 也很简单

  <div id='container'>
<div id='child1'></div>
<table id='table1'>
<tbody></tbody>
</table>
<div id='child2'></div>
</div>

表格有一些设置其高度的内容。呈现页面时,父容器 div 的高度设置为表的高度,这是应该的。然而,其他 child 由于某种原因折叠了。这是示例,为清楚起见,使用了一些表格元素和样式:http://jsfiddle.net/GUEc6/ .如您所见,容器 div 的高度已正确设置为表格的高度,但 child1 和 child2 div 无法将其高度正确设置为该高度的 100%。我知道如果 float 元素的高度设置为 100%,则父元素需要定义自己的高度,这样子元素才能 100% 成为具体的东西。但看起来这并不是这里发生的事情。

最佳答案

这是对 height: 100% 的常见误解。

来自 MDN :

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.

您的问题的一个解决方案可能是绝对定位。在您的容器上设置 position: relative 并绝对定位 child 。设置 top: 0; bottom: 0; 在它们上面会将它们拉伸(stretch)到容器的高度。

Quick Demo (显示概念,您可能需要对其进行调整)

关于HTML div 元素不采用其父级的高度,即使父级具有非零高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435118/

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