【问题标题】:Auto Grid columns, without wrapping to next row自动网格列,不换行到下一行
【发布时间】:2020-12-13 02:13:15
【问题描述】:

我希望这 3 个框彼此相邻显示,并具有相同的 width of 381px

他们的父母是.boxes,他们是.box

我可以在父级上使用以下内容:

.boxes {
   display: grid;
   grid-template-columns: repeat(3, 381px);
}

但是

如果将来我想再添加一个框,我希望 .box 也有 381 像素宽。

我不想指定数字 3,如果出现新框,我希望它是 381px 的无限列

我想达到与以下相同的结果:

grid-template-columns(auto-fit, 381px);

但我不想让它们换到下一行,如果它们放不下的话。

有可能吗?

【问题讨论】:

    标签: css css-grid


    【解决方案1】:

    使用以下几行代码将帮助您实现这一目标

    .boxes {
        display: grid;
        gap: 10px;
        grid-auto-columns: 381px;
        grid-auto-flow: column; 
    }
    

    grid-auto-flow 属性定义添加到网格的新元素是作为“隐式行”还是“隐式列”添加。默认是行,我们希望是列。

    grid-auto-columns 属性与grid-template-columns 相同,只是它处理隐式列(第 4 列及以后,因为您将网格定义为只有 3 列,这 3 列之后的列将是隐式列) .

    【讨论】:

      【解决方案2】:

      您只需将流设为如下所示的列:

      .boxes {
        display: grid;
        grid-auto-columns: 381px;
        grid-auto-flow: column; /* this will do the trick */
        grid-gap: 10px;
      }
      
      .boxes>* {
        height: 50px;
        background: red;
      }
      <div class="boxes">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-17
        • 2021-05-24
        相关资源
        最近更新 更多