Grid gap percentage without height

不想你离开。 提交于 2019-12-02 01:08:59

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:

CSS Grid - unnecessary word break

Why does percentage padding break my flex item?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!