css 创建一个网格,其中网格项具有最大宽度,但在设备宽度上的间距仍然相等

kse8i1jr  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(162)

我在努力创造一个(2行-3列)网格,间距为1fr 1fr 1fr。每个网格项内都有一个<img>,间距为max-width: 512px。我给了网格一个margin: 0 3.75rem。现在我遇到了网格项大于网格项内容的问题(512px)。如何使网格具有与justify-content: space-between;的Flexbox相同的视觉外观?是否存在"间隙:自动"-变通方案?
我拥有的与我想要的:

这是我目前掌握的资料:

#grid {
    margin: 0 3.75rem;
    display: grid;
    grid-template:
    "1 2 3" auto
    "4 5 6" auto / 1fr 1fr 1fr;
    width: 100%;

.gridItem {
    height: 56rem;
    border: 1px solid #000000;
}

.img {
    width: 100%;
    max-width: 512px;
    height: auto;
    border: 1px dashed #cb34ed;

}
<div id="grid">
    <div id="1" class="gridItem"><div class="img"></div></div>
    <div id="2" class="gridItem"><div class="img"></div></div>
    <div id="3" class="gridItem"><div class="img"></div></div>
    <div id="4" class="gridItem"><div class="img"></div></div>
    <div id="5" class="gridItem"><div class="img"></div></div>
</div>

我知道我可以将它们拆分成2个Flexbox行,并给它们justify-content: space-between;,但我需要它是一个网格!有人能帮忙吗?我只是想不通...

e3bfsja2

e3bfsja21#

使用herehere中所述的第n个子代的函数表示法。

  • justify-items: center;在网格本身上
  • justify-self: start;,从第一个项目开始,每隔一个网格项目
  • justify-self: end;,用于从第三个项目开始的每第三个网格项目
#grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1em;
  justify-items: center;
  border: 2px solid cyan;
}

.gridItem {
  border: 2px solid red;
  height: 10rem;
}

/* for every 3rd item starting with the first one */
.gridItem:nth-child(3n+1) {
  border: 2px solid yellow;
  justify-self: start;
}

/* for every 3rd item starting with the third one */
.gridItem:nth-child(3n+3) {
  border: 2px solid blue;
  justify-self: end;
}

.gridItem img {
  width: 100px;
}
<div id="grid">
    <div id="1" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
    <div id="2" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
    <div id="3" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
    <div id="4" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
    <div id="5" class="gridItem"><img src="https://shotkit.com/wp-content/uploads/2020/08/night-landscape-photography-featured.jpg"></div>
</div>

如果你愿意用auto代替1fr来设置列宽,你甚至可以像使用flexbox一样使用justify-content: space-between;,这个解决方案很好很简单。
一个二个一个一个

相关问题