我有一个这样的 html 布局:
,-------------.
|,-----------.|
|| child 1 ||
|`-----------'|
|,-----------.|
|| child 2 ||
|| ||
|| ||
|| ||
|| ||
|`-----------'|
`-------------'
容器被赋予一个高度值,比如说 100vh
,child 1
有一个固定的高度。我希望 child 2
自动填充剩余高度。
我知道有一个 flexbox 解决方案:
.container {
display: flex;
flex-direction: column;
}
.child-1 {
flex-shrink: 0;
flex-grow: 0;
}
.child-2 {
flex-grow: 1;
}
该解决方案单独使用,但如果我想要 child 2
中的第三个 child 3
具有 height: 100%
,它失败。我需要使 child 2
flex 并将 child 3
设置为 flex-grow: 1
。
随着嵌套的加深,这种 flex 继承变得非常令人沮丧。它还违反了“关注点分离”,因为 DOM 结构仅在所有节点都正确设置为 display: flex
时才起作用。
下面是演示问题的 jsfiddle。
html,
body {
margin: 0;
}
div {
width: 100%;
}
.container {
height: 100vh;
display: flex;
flex-direction: column;
}
.child-1 {
height: 50px;
flex-shrink: 0;
flex-grow: 0;
}
.child-2 {
flex-grow: 1;
}
.child-3 {
height: 80%;
}
/* irrelevant styles like background-color etc. */
.container.irrelevant {
width: 100px;
background: green;
float: left;
margin-right: 20px;
}
.child-1.irrelevant {
background: red;
}
.child-2.irrelevant {
background: magenta;
}
.child-3.irrelevant {
background: yellow;
}
<div class="container irrelevant">
<div class="child-1 irrelevant">
Child 1
</div>
<div class="child-2 irrelevant">
Child 2<br> Seems like it works
</div>
</div>
<div class="container irrelevant">
<div class="child-1 irrelevant">
Child 1
</div>
<div class="child-2 irrelevant">
Child 2
<div class="child-3 irrelevant">
But it doesn't, child 3 should fill 80% height of the child 2.
</div>
</div>
</div>
最佳答案
哦,您可以为此使用 calc。像这样的东西;
.child-2 { height: calc(100vh - 100px); }
假设 .child-1
的固定高度是 100px
。
如果您想要更动态的东西,请使用@patelarpan 的解决方案,但这既快速又简单(而且不脏)。
关于html - 如何在不使用 flexbox 的情况下让 <div> 填充剩余高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350971/