CSS fit-content 和 max-content 有什么区别?

What is the difference between CSS fit-content and max-content?

我正在阅读这篇文章 https://css-tricks.com/almanac/properties/w/width/ 以尝试了解此规则的工作原理。

我有这个例子:

*{margin:0; padding:0}
.box{
  background: lightgreen;
  margin: 0 auto;
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
}
<div class="box">
  <img src="https://tyrannyoftradition.files.wordpress.com/2012/05/cutest-kitten-hat-ever-13727-1238540322-17.jpg" alt="" />
  <figure>Yes, put some text here that is wider than the image above to try some new rules</figure>
</div>

文章说 fit-content 可用于将宽度未知的 div 与 margin: x auto;

居中

但是,如果您在此示例中将 fit-content 更改为 max-content,这仍然有效,并且它们似乎总是以相同的方式运行。

有谁知道这两个规则有什么区别,在什么情况下我应该使用一个或另一个?

正如您在此处看到的那样 https://developer.mozilla.org/en-US/docs/Web/CSS/width max-width 只是根据其 children 的 space 需求设置大小,而不管它是否可用,而fit-width 检查 children 需要使用 max-width 的 space 是否可用,如果不可用,则使用 min-width 代替。 如需进一步了解 max-width 和 min-width 之间的区别,请参阅 http://dev.w3.org/csswg/css-sizing/#block-intrinsic

fit-content 使用 max-content除非 available < max-content,然后它使用 available除非 available < min-content,那么它使用min-content.

max-content 和 fit-content 行为不同的一种情况是当您将 'max-width' 属性 设置为元素,并且视口大小小于最大宽度值。在这种情况下,'max-content' 值将导致文本将被任意剪切的布局(查看整个文本的唯一方法是水平滚动)。另一方面,使用 'fit-content' 值将忽略最大宽度 属性 并在视口内很好地调整文本。

简而言之 width: fit-content; 意思是:

"Use the space you can (available) but never less than your min-content and never more than your max-content"

这两个代码好像是一样的:

.fit-content {
  width: fit-content;
}
// is same as
.fit-content {
  width: max-content;
  max-width: 100%;
  min-width: min-content;
}

根据我的经验,我会选择 width: fit-contentwidth: max-content; max-width: 100%。后者适用于元素不应具有 min-width 的情况。后者也等于 width: fit-content; max-width: 100%