具有自动填充和自动大小的CSS网格

时间:2020-01-28 19:49:58

标签: css css-grid

我正在尝试将CS​​S网格与 grid-template-columns:重复(自动填充,自动)一起使用,将单元格设置为最大宽度,从而导致每行一项。

>

是否可以通过项目宽度自动设置网格单元格的宽度?我已经尝试了inline-grid / grid-auto-flow:列,但是项目不包含这些属性。

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, auto);
  color: #444;
}

.box1 {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
  width: 250px;
}

.box2 {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
  width: 350px;
}
<div class="wrapper">
  <div class="box1 a">A</div>
  <div class="box1 b">B</div>
  <div class="box2 c">C</div>
  <div class="box2 d">D</div>
  <div class="box1 e">E</div>
  <div class="box2 f">F</div>
  <div class="box1 g">G</div>
  <div class="box2 h">H</div>
  <div class="box1 i">I</div>
  <div class="box2 j">J</div>
  <div class="box2 k">K</div>
  <div class="box2 l">L</div>
  <div class="box1 m">M</div>
</div>

1 个答案:

答案 0 :(得分:1)

只需移动grid-template-columns内元素的宽度

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 250px);
  color: #444;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
  <div class="box g">G</div>
  <div class="box h">H</div>
  <div class="box i">I</div>
  <div class="box j">J</div>
  <div class="box k">K</div>
  <div class="box l">L</div>
  <div class="box m">M</div>
</div>