在 CSS-grid 上设置 grid-gap 以自动填充可用的水平空间

Ced*_*ore 9 html css sass css-grid

我正在尝试计算 Css 网格的“grid-gap”属性,以使用 Sass 填充所有可用空间。

描写

这是我的设置。

//Don't want to use javascript
Run Code Online (Sandbox Code Playgroud)
//scss
$width: 250px;
.product-grid {
  $total: 100%;
  $count: 4; // <--- hardcoded value, I want this to be calculated automatically 
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: repeat(auto-fill, minmax($width, 1fr));
  max-height: $count;
  grid-gap: calc(calc(#{$total} - calc(#{$count} * $width)) / (#{$count - 1}));
}

.product {
  width: $width;
  height: 406px;
  background:red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="product-grid">
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我目前能够计算出产品适合的“网格间隙”应该有多大,前提是我给出了容器中可以容纳的列数 -“$count”。如果我能够以某种方式计算“$count”,我就完成了。

我尝试过的

$count: floor(calc(#{$total} / #{$width})); //but this won't work because the result is not a 'Number'
Run Code Online (Sandbox Code Playgroud)

dee*_*wan 7

不建议使用网格来创建该行为。Flexbox 是最好的解决方案,使用justify-content: space-between

.product-grid {
  display: flex;
  justify-content: space-between;
  width: 500px;
  border: 1px solid blue;
}

.product {
  width: 50px;
  height: 50px;
  background:red;
  border: 1px solid yellow;
}
Run Code Online (Sandbox Code Playgroud)
  <div class="product-grid">
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
  </div>
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我尝试将 flex-wrapping 设置为wrapper,这样它会自动将不适合的产品放在下一行,问题是,当最后一行中的产品数量少于列时,间距就会变大搞砸了,你最终会得到这样的结果:https://pasteboard.co/JF2hDYdk.png (6认同)
  • 有没有使用网格的解决方案?我有相同的设置,但也需要多行。 (2认同)