【发布时间】:2026-01-16 08:20:03
【问题描述】:
在下面的代码中,孩子的(inline-block) 宽度扩展到其父计算宽度的 100%,但我不知道为什么 .child 的 height 没有扩展到 .parent's 计算高度。
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.ancestor {
height: 250px;
border: 1px solid green;
}
.parent {
display: block;
padding: 20px;
border: 1px solid #474747;
background-color: #fff;
}
.child {
display: inline-block;
width: 100%;
height: 100%;
background-color: pink;
}
<div class="ancestor">
<div class="parent">
<p class="child">
Lorem ipsum dolor sit amet, consectetur adipisicing.
</p>
</div>
</div>
我更感兴趣的是了解这种行为背后的逻辑,而不是解决方案。有人可以解释一下这种情况。
谢谢
【问题讨论】:
-
因为流入元素的百分比高度基于父元素的高度。而且由于您没有在父级上定义高度,因此它计算为
auto。请参阅我在副本中的答案以获得完整的解释:Working with the CSSheightproperty and percentage values.
标签: css box-sizing