将百分比用作网格间距时,CSS网格高度错误

时间:2018-11-03 03:16:10

标签: html css css-grid

我正在使用其中包含图像的CSS网格,并希望在元素之间设置一个随网格大小缩放的间隙。因此,我将grid-gap设置为2%,但是这样做会导致网格高度错误,并使网格内容与下面的下一个元素重叠。像vw一样,将其他单位用作grid-gap也可以。

如果我想使用百分比作为差距,如何解决重叠问题?

以下是我遇到的问题的简要再现:

.grid {
  display: grid;
  grid-template-columns: repeat(2, auto);
  grid-gap: 10%;
  background-color: #EEE
}

.grid-item {
  display: block;
  width: 100%;
}
<div class="grid">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
</div>
<p>Why does this line overlap with the grid?</p>

1 个答案:

答案 0 :(得分:0)

这10%的人似乎很喜欢弹性。

.container {
   width:90%;
   margin:0 auto;
   display:block;
}

.grid {
  display: flex;
  justify-content:space-between;
  flex-wrap:wrap;
  width:100%;
  background-color: #EEE
}

.grid-item {
  flex:0 0 45%;
  max-width:500px;
  margin:0 0 10% 0;
  display: block;
}

img.grid-item:last-of-type {
   margin-bottom:0;
}
 <div class="container">
<div class="grid">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP839r6HwAHngMKGIKGywAAAABJRU5ErkJggg==" class="grid-item">
</div>
<p>Why does this line overlap with the grid?</p>
</div>