Basically, the container has both fluid height and width. Kindly consider the following:
<div class="container">
<span class="header">Hello!</span>
<div class="box"></div>
<div class="box"></div>
</div>
Both of the box
divs take say 40% height each, assume I apply 15% height for the span
element and the remaining 5% for its margin-top
value. As expected it will not sum up to 100% of the container
height since
margin-top
is calculated based on the width as far as I know. How do I calculate the margin-top
percentage value in this case so all elements including the margin would sum up to the full height of the container
? here's my CSS Code, thanks in advance.
.container {
height: 80%;
width: 80%;
}
.header {
height: 15%;
display: inline-block;
margin-top: 5%; /*how to calculate this correctly*/
}
.box {
height: 40%;
}
I think you can easily obtain what you want by using flexbox and margin-top:auto
on header
:
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>