如何在 css 网格之间使用 justify-content 空间

问题描述 投票:0回答:1

我的整个网站有一个使用 12 列的网格布局 我想要 3 个项目,每个项目占用 3 列,并在它们之间分配重命名空间, 类似于 justify-content: space- Between 是 css flex

我知道我可以在没有CSS网格的情况下做到这一点,只是想知道是否

我可以用 CSS 网格做到这一点 我想要实现这样的目标

enter image description here

html

<div class="grid">
  <div class="grid__item">1</div>
  <div class="grid__item">2</div>
  <div class="grid__item">3</div>
</div>

CSS

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  width: 100%;
  gap: 10px;
  justify-content: space-between;
}

.grid__item {
  grid-column: span 3;
}

.grid__item:nth-child(1) {
  background: red;
}

.grid__item:nth-child(2) {
  background: lightblue;
}

.grid__item:nth-child(3) {
  background: lightgreen;
}
html css css-grid
1个回答
0
投票

您必须计算 div 的宽度,然后将它们对齐到

grid-area
位置。

 width: calc((100vw - (10px * 11))/4);

10px 是间隙,11 是基于列数的间隙数,4 是 12 除以元素数。

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-template-areas: "a a a b b b b b b c c c";
  gap: 10px;
  //justify-content: space-between;
}

.grid__item {
  width: calc((100vw - (10px * 11))/4);
  /* 10px is the gap, 11 is the number of gaps based on the number of columns, 4 is the 12 divided by the number of elements */
}

.grid__item:nth-child(1) {
  background: red;
  grid-area: a;
}

.grid__item:nth-child(2) {
  background: lightblue;
  grid-area: b;
  justify-self: center;
}

.grid__item:nth-child(3) {
  background: lightgreen;
  grid-area: c;
}
<div class="grid">
  <div class="grid__item">1</div>
  <div class="grid__item">2</div>
  <div class="grid__item">3</div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.