CSS 子网格在元素之间添加了不均匀的空间

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

我正在使用子网格来创建间距均匀的卡片。由于某种原因,卡片在元素之间添加了大量空间,并且 FF 和 Chrome 中的空间不同。以下是基于此教程的代码。

.wrapper{
  margin:0;
  display:grid;
  grid-template-columns:repeat(auto-fit, minmax(350px, 1fr));
  gap:1rem;
  margin-top:0rem;
  max-height:400px;
}
.wrapper p h2 {  margin:0px;}
.wrapper img {
  max-width:100%;
  display:block;
}
.box{
   border:1px solid #ccc;
  border-radius: 6px;
  padding:1rem;
  display:grid;
  grid-template-rows:subgrid;
  grid-row:span 3;
}
<div class="wrapper">
  <div class="box">
    <img src="https://picsum.photos/600/400?random=1" />
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <img src="https://picsum.photos/600/400?random=4" />
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <img src="https://picsum.photos/600/400?random=3" />
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <img src="https://picsum.photos/600/400?random=2" />
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
</div>

html css css-grid
1个回答
0
投票

这是因为你如何限制图像大小。轨道高度是在图像高度受

width:100%
限制之前计算的。

为了处理因替换 grid/flex 容器下的元素而引起的问题,我总是尝试将其包装在包装器下。

.wrapper {
  margin: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 1rem;
  margin-top: 0rem;
  max-height: 400px;
}

.wrapper p h2 {
  margin: 0px;
}

.box>div {
  max-width: 100%;
}

img {
  max-width: 100%;
  display: block;
}

.box {
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 1rem;
  display: grid;
  grid-template-rows: subgrid;
  grid-row: span 3;
}
<div class="wrapper">
  <div class="box">
    <div>
      <img src="https://picsum.photos/600/400?random=1" />
    </div>
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <div>
      <img src="https://picsum.photos/600/400?random=4" />
    </div>
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <div>
      <img src="https://picsum.photos/600/400?random=3" />
    </div>
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
  <div class="box">
    <div>
      <img src="https://picsum.photos/600/400?random=2" />
    </div>
    <h2>This is Title One</h2>
    <p>This is the short description of the article which will be used for now</p>
  </div>
</div>

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