此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

fit-content

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2021年11月⁩.

fit-content 关键字相当于 fit-content(stretch)。在实际应用中,这意味着盒子会使用可用空间,但绝不会超过 max-content

当用作 widthheightmin-widthmin-heightmax-widthmax-height 的布局盒子尺寸时,最大和最小尺寸指的是内容尺寸。

可以使用 interpolate-size 属性和 calc-size() 函数来启用由 fit-content 开始或结束的动画。

备注:CSS 尺寸规范另外还定义了 fit-content() 函数。本页详细介绍了该关键字的用法。

语法

css
width: fit-content; block-size: fit-content; 

示例

使用 fit-content 调整盒子大小

HTML

html
<div class="container"> <div class="item">项目</div> <div class="item">项目中包含更多文本。</div> <div class="item"> 项目中包含更多文本,希望我们已经添加了足够的文本,以便文本开始换行。 </div> </div> 

CSS

css
.container { border: 2px solid #ccc; padding: 10px; width: 20em; } .item { width: fit-content; background-color: #8ca0ff; padding: 5px; margin-bottom: 1em; } 

结果

规范

Specification
CSS Box Sizing Module Level 4
# valdef-width-fit-content

浏览器兼容性

参见