I'd like to have a grid like this:
.grid{
display:grid;
grid-gap:50%;
background-color:blue;
}
.grid-1{
background-color:red;
}
<div class="grid">
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
</div>
I think it's a really big problem by all browser to correctly understand percentage values How to resolve this?
Markus
Since we cannot resolve the percentage initially, the grid is first calculating the height considering content like this:
console.log(document.querySelector('.grid').offsetHeight)
.grid {
display: grid;
background-color: blue;
}
.grid-1 {
background-color: red;
opacity:0.5;
}
<div class="grid">
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
</div>
Then using this height the gap will be calculated and then added to the grid. This will not trigger the height calculation of the grid again as it will create a cycle thus the overflow you have.
console.log(document.querySelector('.grid').offsetHeight)
console.log(document.querySelector('.grid-1:nth-child(2)').offsetTop - document.querySelector('.grid-1:nth-child(1)').offsetTop - document.querySelector('.grid-1:nth-child(1)').offsetHeight)
.grid {
display: grid;
grid-gap:100%;
background-color: blue;
margin-top:50px;
}
.grid-1 {
background-color: red;
opacity:0.5;
transform:translateY(-100%);
}
<div class="grid">
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
</div>
As you can see, I used 100% and added some transfomation to see that the gap is equal to the initial height (the JS code also confirm this).
A trivial fix is to avoid percentage values and use pixel values so that the browser will include them in the initial calculation. In all the cases, using percentage value isn't good is such situation as you don't know "percentage of what?"
.grid {
display: grid;
grid-gap:50px;
background-color: blue;
margin-top:50px;
}
.grid-1 {
background-color: red;
opacity:0.5;
}
<div class="grid">
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
<div class="grid-1">
test
</div>
</div>
Here is more examples where percentage values are evaluated later and create unwanted results:
来源:https://stackoverflow.com/questions/53563613/grid-gap-percentage-without-height