小,大:使用CSS fit-content

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-fitmax-contentmin-content 。 尽管这些值仍被正式标记为“实验性”,但当提供适当的供应商前缀时,这些值就具有出色的浏览器支持。

Existing somewhere between max-content and min-content, fit-content can be very helpful, particularly when creating responsive designs.

fit-content存在于max-contentmin-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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值