所有宽度设置为最宽元素的宽度

All widths set to width of widest element

我已经阅读了很多关于 CSS 弹性框和 CSS 网格的教程,但坦率地说,我就是不知道如何做这个简单(?)的事情。

我只想让容器中的元素都与最宽的元素一样宽。

我不希望它们填满容器的整个宽度,只是全部增长到最大宽度。可以用 CSS 来完成吗?

考虑这个 HTML:

<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button>a really, really, really wide button</button>
</div>

产生这样的东西:

我想要的是这样的,它们都是最宽按钮的宽度:

我不希望它们只是伸展以填满页面的宽度:

这能做到吗?如果是这样,上面 HTML 的 CSS 是多少?

是的。这可以用纯 CSS.

来完成

这是一个简单的解决方案:

.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;
}
<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button>a really, really, really wide button</button>
</div>

工作原理如下:

网格布局提供了一个单元,用于在网格容器中建立灵活的长度。这是 fr 单元。它旨在在容器中免费分发space(有点类似于flex-grow)。

但是,当容器的宽度/高度是动态的(例如,在本例中为 display: inline-grid)时,网格规范提供了一种特别独特的行为。

在这种情况下,fr 单元将计算每个网格项目的 max-content。然后它将取它找到的最大值并将其用作轨道上所有项目的 1fr 长度。

这会导致网格项目共享行中最宽项目的宽度。

奇怪,但确实如此。

这也是为什么布局

这是规范中的相关部分:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

这是一个使用 CSS 网格和任意数量按钮的解决方案:

div.container {
  display: inline-grid;
  grid-auto-columns: 1fr;
}

div.container button {
  grid-row: 1;
}