我正在关注这篇文章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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
文章说,fit-content可以用来将未知宽度的div居中 margin: x auto;
但是如果你在这个例子中更改了max-content的fit-content,那么无论如何它都会起作用,并且它们似乎总是以相同的方式运行.
有谁知道这两条规则之间有什么区别,我应该在哪些情况下使用其中一条规则?
jig*_*jer 23
fit-content使用max-content,除非 available < max-content它使用可用.除非 available < min-content,然后它使用min-content.
小智 7
max-content 和 fit-content 行为方式不同的一种情况是,当您在元素上设置 'max-width'属性时,并且视口大小小于 max-width 值。在这种情况下,'max-content' 值将导致文本被任意剪切的布局(查看整个文本的唯一方法是水平滚动)。另一方面,使用 'fit-content' 值将忽略 max-width 属性并在视口内很好地调整文本。
如您在这里所见,https://developer.mozilla.org/zh-CN/docs/Web/CSS/width最大宽度仅根据其子级所需的空间来设置大小,而不管其是否可用。 fit-width检查是否有孩子需要使用max-width的空间,如果没有,则使用min-width。有关最大宽度和最小宽度之间差异的更多信息,请参见http://dev.w3.org/csswg/css-sizing/#block-intrinsic。
看起来这两个代码是相同的:
.fit-content {
width: fit-content;
}
// is same as
.fit-content {
width: max-content;
max-width: 100%;
min-width: min-content;
}
Run Code Online (Sandbox Code Playgroud)
根据我的经验,我要么选择width: fit-content要么width: max-content; max-width: 100%。后者适用于元素不应具有最小宽度的情况。