max-content

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

max-content 尺寸關鍵字表示元素的最大固有尺寸。該關鍵字將元素擴充套件到顯示其內容所需的、不進行任何軟換行的最大尺寸。對於文字內容,此關鍵字根本不會換行,即使這會導致溢位。

interpolate-size 屬性和 calc-size() 函式可用於啟用到和從 max-content 的動畫。

語法

css
/* Used as a length value */
width: max-content;
inline-size: max-content;
height: max-content;
block-size: max-content;

/* Used in grid tracks */
grid-template-columns: 200px 1fr max-content;

示例

使用 max-content 調整盒子尺寸

HTML

html
<div id="container">
  <div class="item">Item</div>
  <div class="item">
    Item with more text in it which will overflow the fixed width box.
  </div>
</div>

CSS

css
#container {
  background-color: #8cffa0;
  padding: 10px;
  width: 200px;
}

.item {
  width: max-content;
  background-color: #8ca0ff;
  padding: 5px;
  margin-bottom: 1em;
}

結果

使用 max-content 調整網格列尺寸

HTML

html
<div id="container">
  <div>Item</div>
  <div>Item with more text in it.</div>
  <div>Flexible item</div>
</div>

CSS

css
#container {
  display: grid;
  grid-template-columns: max-content max-content 1fr;
  grid-gap: 5px;
  box-sizing: border-box;
  height: 200px;
  width: 100%;
  background-color: #8cffa0;
  padding: 10px;
}

#container > div {
  background-color: #8ca0ff;
  padding: 5px;
}

結果

規範

規範
CSS Box Sizing Module Level 3
# valdef-width-max-content

瀏覽器相容性

另見