如何让弹性项目的孩子占父母身高100%?



我有一个简单的页面,带有标题(需要占总页面高度的20%)和容器,我想填充剩余的页面高度(80%)。

问题是我希望容器的每个子级都是容器高度的 100%(因此容器需要扩展到实际占总页面高度的 80% * 有多少个子级。

是否可以使用 Flexbox 使容器容纳多个元素,每个元素都是容器的总高度?

我不知道如何使元素既填充剩余空间,又将其用作总高度的指标。

无论如何,这里有一个代码笔演示 - 简单的 html 和 css 如下: 我理想的结果是每个彩色divs都是body的完整高度减去header高度,容器将扩展以容纳项目。

任何想法将不胜感激。

html, body {
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
}
header {
background: blue;
flex: 1;
}
div.holder {
flex: 5;
display: flex;
flex-direction: column;
}
div.one {
flex: 1;
background: green;
}
div.two {
flex: 1;
background: yellow;
}
div.three {
flex: 1;
background: red;
}
div.four {
flex: 1;
background: orange;
}
<body>
<header>  
</header>
<div class="holder">
<div class="one">
one
</div>
<div class="two">
two
</div>
<div class="three">
three
</div>
<div class="four">
four
</div>
</div>
</body>

演示

.css

html, body {
height: 100%;
margin: 0;
}
header {
background: blue;
height:20%
}
div.holder {
height:80%; /* <------ make it of desired height */
display: flex;
flex-direction: column;
align-items: stretch;
}
div.holder > div {
min-height: 100%; /* <------ better to provide min-height */
}
div.one {
flex: 1;
background: green;
}
div.two {
flex: 1;
background: yellow;
}
div.three {
flex: 1;
background: red;
}
div.four {
flex: 1;
background: orange;
}

.html

<body>
<header></header>
<div class="holder">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
<div class="four">four</div>
</div>
</body>

你真的需要弹性盒吗?
为什么不简单地使用视口值(vw,vh)?

html, body {
margin: 0;
}
header {
background: blue;
height: 20vh;
}
div.holder {
height: 80vh;
}
div.one {
background: green;
height: 100%;
}
div.two {
background: yellow;
height: 100%;
}
div.three {
background: red;
height: 100%;
}
div.four {
background: orange;
height: 100%;
}
<body>
<header>  
</header>
<div class="holder">
<div class="one">
one
</div>
<div class="two">
two
</div>
<div class="three">
three
</div>
<div class="four">
four
</div>
</div>
</body>



或者你可以使用百分比值,它几乎是一样的。(但正文和 html 需要有 100% 的高度)

html, body { height: 100%; }
header { height: 20%; }
.holder { height: 80%; }
.holder > div { height: 100%; }

最新更新