CSS设置height: 100%不生效

父元素没有固定高度的时候,子元素设置height: 100%不生效。但是可以通过flexbox布局或者grid布局来让元素自动填充剩余宽度或者高度。

html:

1
2
3
<div class="parent">
<div class="child"></div>
</div>

css:

1
2
3
4
5
6
7
8
9
10
.parent {
display: flex;
flex-direction: column; /* 确保子元素在父元素内垂直排列 */
}

.child {
flex-grow: 1; /* 让子元素填充剩余空间 */
/* 或者使用 flex: 1; 也可以实现同样的效果 */
}