I will need some help for the template of my website I’m lost with CSS heights and how they are made.
To understand my issue better I’ve created an codepen where its possible to visualise my issue in a simple way link
* {
margin: 0;
}
.container {
height: 100vh;
background: red;
width: 100wh;
over-flow: hidden;
padding: 1.25rem;
box-sizing: border-box;
}
.container2 {
border: 2px solid black;
height: 100%;
background-color: blue;
}
.boxtop {
with: auto;
height: 20px;
background-color: pink;
}
.gridcontainer {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
height: 100%;
}
.box {
grid-column: span 4 / span 4;
background-color: yellow;
height: 100%;
}
<div class="container">
<div class="container2">
<div class="boxtop"></div>
<div class="gridcontainer">
<div class="box">d</div>
<div class="box">d</div>
</div>
</div>
</div>
In this link you will see that the yellow part goes way over and I want it to stop at the end of the blue part.
Each box should have the height of container2
– boxtop
Thanks for your help.
4
Answers
To fix this update
box
height to thisheight: calc(100% - 20px);
. Also,with
andover-flow
are invalid CSS properties.wh
is invalid CSS unit. Update it tooverflow: hidden;
The problem lies in the height calculation of the yellow box within the grid container. Here’s the updated code to fix the issue:
.container2
, I addeddisplay: flex;
andflex-direction: column;
to ensures that the container expands vertically to match the height of its parent container..gridcontainer
, I addedflex: 1;
. This allows the grid container to expand and take up the remaining vertical space within.container2
.height: 100%;
from.box
as it was causing the yellow box to expand beyond the intended limits.First of, some typos:
wh
is an invalid unit,with
is notwidth
,over-flow
should beoverflow
flex
20px height
if you’ll have content in the.boxtop
. Let flex calculate the necessary spaces for youdvh
unit for dynamic viewport heightYou will need to choose the units properly so that they are compatible with each other. For example, in your original code, you have set the container height in vh units, padding in rem units, boxtop in px units, and box height in % units. That is not helping you make the calculations needed to visualize the element sizes. If instead you measured all of the above in vh units, you could do something like this:
Here, I have kept the total height as 100vh, padding top and bottom I have applied 5vh each, and the boxtop height is 5vh. So the box height, in order to fit the grid, should have to be (100-5-5-5)vh or 85vh. This should also be responsive if you resize the window because all the elements use the same vertical height unit. Hope this helps.