In previous articles I’ve explored some of the new intrinsic and extrinsic CSS values such as object-fit
, max-content
and min-content
. While still officially labeled “experimental”, these values have excellent browser support when provided with appropriate vendor prefixes.
在先前的文章中,我探讨了一些新的内在和外在CSS值,例如object-fit
, max-content
和min-content
。 尽管这些值仍被正式标记为“实验性”,但当提供适当的供应商前缀时,这些值就具有出色的浏览器支持。
Existing somewhere between max-content
and min-content
, fit-content
can be very helpful, particularly when creating responsive designs.
fit-content
存在于max-content
和min-content
之间可能非常有帮助,尤其是在创建响应式设计时。
收缩包装而不会捕捉 (Shrink-Wrapping Without Snapping)
min-content
is excellent for aligning groups of content with unknown width, such as a site navigation bar:
min-content
非常适合用于对齐宽度未知的内容组,例如网站导航栏 :
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>
With the following CSS:
使用以下CSS:
nav { background: #555; }
nav a {
display: inline-block;
padding: 1rem;
text-transform: uppercase;
color: #fff;
text-decoration: none;
}
By default, the navigation bar will look something like this:
默认情况下,导航栏将如下所示:
Rather than taking the entire width of its parent, what if we want to collapse the bar down to its smallest possible width, without breaking any of the links onto a new line? We can achieve that with fit-content
:
如果不希望将条形图折叠到其最小可能的宽度, 而又不将任何链接断开到新行上,而不是采用其父项的整个宽度,该怎么办? 我们可以通过fit-content
实现:
nav { background: #555; width: fit-content; }
Now we gain the ability to center-align the navigation bar, despite never setting an explicit width on it:
现在,我们可以对导航栏进行居中对齐,尽管从未在其上设置显式宽度:
nav { margin: 0 auto; }
The result:
结果:
This can also work for images and other replaced elements:
这也适用于图像和其他替换的元素:
figure {
border: 2px solid #222;
width: fit-content;
background: #555;
font-size: 0;
}
figure img {
width: 200px;
}
翻译自: https://thenewcode.com/975/Little-Big-Using-CSS-fit-content