fit-content
fit-content 尺寸关键字表示元素的尺寸可适应其内容,同时保持在其容器的限制范围内。该关键字确保元素绝不会小于其最小内在尺寸(min-content),也绝不会大于其最大内在尺寸(max-content)。
注意:此关键字与 fit-content() 函数不同。该函数用于网格轨道尺寸(例如在 grid-template-columns 和 grid-auto-rows 中),以及用于属性(如 width、height、min-width 和 max-height)的布局框尺寸。
语法
css
/* Used in sizing properties */
width: fit-content;
height: fit-content;
inline-size: fit-content;
block-size: fit-content;
描述
此关键字与尺寸属性(如 width、height、block-size、inline-size、min-width 和 max-width)一起使用。当用于这些属性时,计算出的尺寸指的是元素的内容框。
当设置 fit-content 时,元素会增长或收缩以适应其内容,但在相关维度达到其容器的尺寸限制后停止扩展。
fit-content 尺寸使用以下公式计算
min(max-content, max(min-content, stretch))
其中,stretch 将元素的外边距框与它的包含块的宽度匹配。该关键字本质上等同于 fit-content(stretch)。
你可以使用 interpolate-size 属性和 calc-size() 函数启用到和从 fit-content 的动画。
示例
使用 fit-content 调整框的大小
HTML
html
<div class="container">
<div class="item">Item</div>
<div class="item">Item with more text in it.</div>
<div class="item">
Item with more text in it, hopefully we have added enough text so the text
will start to wrap.
</div>
</div>
CSS
css
.container {
border: 2px solid #cccccc;
padding: 10px;
width: 20em;
}
.item {
width: fit-content;
background-color: #8ca0ff;
padding: 5px;
margin-bottom: 1em;
}
结果
规范
| 规范 |
|---|
| CSS Box Sizing Module Level 4 # valdef-width-fit-content |
浏览器兼容性
加载中…
另见
- 相关尺寸关键字:
min-content、max-content - CSS 盒模型尺寸模块