css 父级div overflow-y: scroll; height: 100%; 子级div height: 2rem; 但是父级高度还是填充不起来 怎么解决
时间: 2024-03-05 18:50:12 浏览: 19
如果父级 div 的高度设置为 100%,则它的高度应该是相对于其父级元素的高度来设置的。所以,为了使父级 div 的高度填充整个父元素,你需要确保其父级元素的高度也是固定的或者使用 flex 布局。例如:
```
<body>
<div class="grand-parent">
<div class="parent">
<div class="child"></div>
</div>
</div>
</body>
<style>
.grand-parent {
height: 100vh; /* 设置为窗口高度 */
}
.parent {
height: 100%; /* 100% 相对于 .grand-parent 高度 */
overflow-y: scroll;
}
.child {
height: 2rem;
}
</style>
```
如果 .grand-parent 的高度不是固定的,你可以使用 flex 布局。如下所示:
```
<body>
<div class="grand-parent">
<div class="parent">
<div class="child"></div>
</div>
</div>
</body>
<style>
.grand-parent {
display: flex; /* 使用 flex 布局 */
flex-direction: column; /* 设置主轴方向为垂直方向 */
height: 100vh; /* 设置为窗口高度 */
}
.parent {
flex: 1; /* 填充剩余空间 */
overflow-y: scroll;
}
.child {
height: 2rem;
}
</style>
```
这样可以让 .parent 元素自适应 .grand-parent 元素的高度,填充整个 .grand-parent 元素。