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 盒模型尺寸模組