css - 在 CSS Grid 中将列宽设置为内容宽度

标签 css css-grid

我希望每个网格元素都适合它的内容宽度(400px),并保持自动填充。我该怎么做?

body {
  margin: 0px;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, auto));
  grid-gap: 10px;
  width: 100%;
}
<div class="container">
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
</div>

最佳答案

只需将 minmax(240px, auto) 替换为固定宽度 400px

请注意,当视口(viewport)的宽度不是 400 的精确倍数时,这会产生间隙,但仍会添加元素以尽可能多地填充空间。

body {
  margin: 0px;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, 400px);
  grid-gap: 10px;
  width: 100%;
}
<div class="container">
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
  <div style="background: aqua; height: 100px;">
    <div style="width: 400px; height: 100px;"></div>
  </div>
</div>

关于css - 在 CSS Grid 中将列宽设置为内容宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56980999/

相关文章:

javascript - Bootstrap 移动导航下拉菜单在打开时跳转

CSS 网格模板全宽行

css - 只允许 css-grid 中的一部分行自动收缩

html - 如何使用 CSS 网格布局在 CSS 中制作固定列?

html - 如何在CSS上设置不同的行宽

css - <audio> 标签的自定义 CSS?

javascript - IIS7 中的 HttpCompression

html - IE11 内联菜单样式不起作用

html - 如何底部对齐 div 行中的所有元素?

CSS grid-template-rows 在悬停时自动将滚动位置重置到底部