How do min-content and max-content work?

如何用 CSS 计算 min-contentmax-content值?

本征维度是什么意思?

69782 次浏览

Note: "width" in this text refers to the "logical width", not CSS's width; that is, the values are also valid for CSS's height, if the language direction is vertical (like east-asian languages) or in flexbox or grid. min-content and max-content are valid values for width, height, min-width, min-height, max-width, max-height and even more properties (like height0).

盒子的固有尺寸是多少?

CSS 尺寸级别3引入了 内在的尺寸的概念——与 外在的相反。盒子的 外在的尺寸是在盒子的父盒子上计算的。例如,width: 80%被称为 外部尺寸外部尺寸,因为主体的 width依赖于其包含盒的 width

与此相反,称 width: min-content内在的,因为盒子的宽度是根据盒子本身包含的内容的尺寸计算的。

内部维度是盒子本身的属性,外部维度只有在盒子放置在文档中并且上下文允许计算这些值的情况下才可用。例如,在 CSS-flow (经典的 CSS 布局模式)中,你可能知道,height: 20%只有在父元素中定义了 height(即它是可继承的)时才有效; 这是一个 外在的维度不可计算的情况(当外部值不可用时,CSS 回退到它的内部等价物)。相反,height: min-content总是可计算的,因为它是 内在的到盒子本身,并且它总是相同的,不管盒子在文档中的位置(或盒子不在)。


这些年来,min-contentmax-content的定义已经改变了很多次,但是结果始终没有改变,而且很容易理解。它们最初是社区作为 width的关键字请求的,当一个盒子是 floating 时,它的计算值将匹配该盒子的宽度。事实上,这两个属性的定义最初是基于 float的行为; 现在它们更通用地定义如下:

min-content

Https://www.w3.org/tr/css-sizing-3/#min-content

一个盒子可以采用的最小尺寸不会导致溢出,这可以通过选择更大的尺寸来避免。

换句话说,盒子的最小宽度,盒子里的东西不会溢出盒子

实际上,可视化这一点的一个好方法是使用 float

/* the computed width of #red in this example
equals to specifying #red { width: min-content } */
#blue        { width: 0px; }
#blue > #red { float: left; }

min-content

(GIF 来源: http://jsfiddle.net/6srop4zu/)

在上面的 GIF 中,the red box's min-content width equals the red box's width at the time the blue box's width is 0px(GIF 中为234px,jsfiddle 中可能不同)。

正如你所看到的,如果红色方块变小,单词 supercalifragilisticexpialidocious就会溢出红色方块,因此在这种情况下,min-content等于该特定单词的宽度,因为它是水平方向占用空间最大的单词。

max-content

Https://www.w3.org/tr/css-sizing-3/#max-content

当给定无限可用空间时,一个盒子在给定轴上的“理想”大小。通常情况下,这是盒子在该轴上可以容纳的最小尺寸,同时仍然围绕其内容进行装配,也就是说,尽量减少未填充的空间,同时避免溢出。

/* the computed width of #red in this example
equals to specifying #red { width: max-content } */


#blue        { width: 99999999999999999px; } /* ~infinite */
#blue > #red { float: left; }

max-content

(GIF 来源: http://jsfiddle.net/nktsrzvg/)

在上面的 GIF 中,红色框的 < em > max-content width 等于当蓝色框的宽度为无限时红色框的宽度(在 GIF 中为386px,在 jsfiddle 中可能不同)。

在这里,红色框充分利用了蓝色框中 x 轴上的可用空间,但没有浪费。内容可以在相关的轴上无限制地展开,红色方框将它们包裹起来,并在最大展开点处展开。


fit-contentstretch和其他的呢?这些物业目前正在重访,因此它们并不稳定(日期: 2018年7月)。他们将被添加到这里,当他们变得更加成熟一点(希望很快)。

最少内容:

The minimum possible width that a content (a group of words) will take. It means width of the biggest word in the content.

例如:

hi this is


biggestWordInTheContent


<---- min-content ---->

最大限度-内容:

一个内容(一组单词)可以承受的最大宽度。它表示所有单词排列在一行中时内容的宽度。

例如:

hi this is a content without considering any line breaks.


<---------------------- max-content ------------------->