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 November 2021.

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: -moz-fit-content;
  background-color: #8ca0ff;
  padding: 5px;
  margin-bottom: 1em;
}

结果

规范

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

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
fit-content

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Uses a non-standard name.
Requires a vendor prefix or different name for use.
Has more compatibility info.

参见