基本上,容器具有流体高度和宽度。请考虑以下事项:
<div class="container">
<span class="header">Hello!</span>
<div class="box"></div>
<div class="box"></div>
</div>
两个 box
div 各占 40% 高度,假设我为 span
元素应用 15% 高度,其余 5% 为其 margin -top
值。正如预期的那样,它不会达到 container
高度的 100%,因为
margin-top
据我所知是根据宽度计算的。在这种情况下,如何计算 margin-top
百分比值,以便包括边距在内的所有元素加起来等于 container
的整个高度?这是我的 CSS 代码,在此先感谢。
.container {
height: 80%;
width: 80%;
}
.header {
height: 15%;
display: inline-block;
margin-top: 5%; /*how to calculate this correctly*/
}
.box {
height: 40%;
}
最佳答案
我认为你可以通过在 header
上使用 flexbox 和 margin-top:auto
轻松获得你想要的东西:
body,html {
height:100%;
margin:0;
}
.container {
height: 80%;
width: 80%;
display:flex;
flex-direction:column;
border:1px solid;
box-sizing:border-box;
}
.header {
flex:0 0 15%;
background:red;
align-self: flex-start; /* To have same visual behavior as inline-block */
margin-top:auto /* this will do the trick*/
}
.box {
flex:0 0 40%;
background:yellow;
}
<div class="container">
<span class="header">Hello!</span>
<div class="box">a</div>
<div class="box">b</div>
</div>
关于html - 计算 margin-top 值以占据流体设计中的剩余高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613606/