如何使用具有百分比和未知数量列的 CSS 网格?

How to use a CSS grid with percentages and an unknown amount of columns?

这是我要实现的布局:

我目前正在通过:

HTML

<div class="ft-Footer_Columns">
  <div class="ft-Footer_Column ft-Footer_Column-about">
    <h4 class="ft-Footer_Title">Title 1</h4>

    <p class="ft-Footer_Text">Text 1</p>
  </div>

  <div class="ft-Footer_Column ft-Footer_Column-links">
    <h4 class="ft-Footer_Title">Title 2</h4>

    <p class="ft-Footer_Text">Text 2</p>
  </div>

  <div class="ft-Footer_Column ft-Footer_Column-contact">
    <h4 class="ft-Footer_Title">Title 3</h4>

    <p class="ft-Footer_Text">Text 3</p>
  </div>
</div>

CSS

.ft-Footer_Columns {    
  display: grid;
  grid-column-gap: calc(20px * 2);
  grid-template-columns: calc(5 / 12)fr calc(4 / 12)fr calc(3 / 12)fr;
}

这似乎是实现我想要的东西的一种很老套的方法。

理想情况下我希望能够做到:

.ft-Footer_Columns {    
  display: grid;
  grid-column-gap: calc(20px * 2);
  grid-template-columns: calc(5 / 12 * 100%) calc(4 / 12 * 100%) calc(3 / 12 * 100%);
}

但目前 100% + ((20px * 2) * 2)

我如何在没有骇人听闻的 calc()FR 方式的情况下实现这种基于百分比/分形的布局?

由于您不知道列数,因此不使用 grid-template-columns 属性。此 属性 定义了一个 显式 网格,这意味着轨道是明确定义的。

您可能正在寻找 grid-auto-columns。此 属性 定义自动创建的列的宽度(这将是 隐式 网格)。

试试这个:

grid-auto-columns: 1fr

对于fr单元,仅分发免费的space。这将是考虑到排水沟后剩下的 space。

7.2.3. Flexible Lengths: the fr unit

A flexible length or <flex> is a dimension with the fr unit, which represents a fraction of the free space in the grid container.

free space

Equal to the available grid space minus the sum of the base sizes of all the grid tracks (including gutters), floored at zero. If available grid space is indefinite, the free space is indefinite as well.

此外 - 当您确实有定义的列数时 - 由于我们处理的是比例,您可以将 fr 值与您想要的百分比相匹配。像这样:

grid-template-columns: 42fr 33fr 25fr (instead of 42% 33% 25%).

这里使用fr的一个好处是会自动扣除gutter的大小(建立免费的space,这是唯一的space fr用途) .对于百分比,您需要使用 calc().

如果您可以为列定义最小宽度值,则以下代码将是建立等宽列而不会溢出的一个很好的解决方案。我在这里定义了 100px 的值,当然,您可以根据需要更改该值。浏览器将尝试通过将宽度缩小到最小宽度来将所有列排成一行。如果有溢出,它会将剩余的列放在第二行。但是列的宽度无论如何都是一样的。

`

.ft-Footer_Columns {
    display: grid;
    grid-column-gap:20px;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

`