max-width

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

max-width CSS 屬性用於設定元素的最大寬度。它阻止 width 屬性的實際值變得大於 max-width 指定的值。

試一試

max-width: 150px;
max-width: 20em;
max-width: 75%;
max-width: 20ch;
<section class="default-example" id="default-example">
  <div class="transition-all" id="example-element">
    Change the maximum width.
  </div>
</section>
#example-element {
  display: flex;
  flex-direction: column;
  background-color: #5b6dcd;
  height: 80%;
  justify-content: center;
  color: white;
}

max-width 會覆蓋 width,但是 min-width 會覆蓋 max-width

語法

css
/* <length> value */
max-width: 3.5em;
max-width: anchor-size(--my-anchor inline, 245px);
max-width: calc(anchor-size(width) + 4em);

/* <percentage> value */
max-width: 75%;

/* Keyword values */
max-width: none;
max-width: max-content;
max-width: min-content;
max-width: fit-content;
max-width: fit-content(20em);
max-width: stretch;

/* Global values */
max-width: inherit;
max-width: initial;
max-width: revert;
max-width: revert-layer;
max-width: unset;

<length>

max-width 定義為一個絕對值。

<percentage>

max-width 定義為包含塊寬度的百分比。

none

盒子大小沒有限制。

max-content

固有的首選 max-width

min-content

固有的最小 max-width

fit-content

使用可用空間,但不超過 max-content,即 min(max-content, max(min-content, stretch))

fit-content(<length-percentage>)

使用 fit-content 公式,並將可用空間替換為指定引數,即 min(max-content, max(min-content, argument))

stretch

將元素外邊距盒的最大寬度限制為其包含塊的寬度。它試圖使外邊距盒填充包含塊中的可用空間,因此在某種程度上與 100% 行為相似,但將結果尺寸應用於外邊距盒,而不是由 box-sizing 決定的盒。

注意:要檢視瀏覽器用於 stretch 值的別名及其實現狀態,請參閱瀏覽器相容性部分。

無障礙

確保當頁面放大以增加文字大小時,設定了 max-width 的元素不會被截斷和/或不會遮擋其他內容。

正式定義

初始值none
應用於除非替換行內元素、表格行和行組之外的所有元素。
繼承性
百分比參照包含塊的寬度
計算值指定的百分比或絕對長度或 none
動畫型別一個長度百分比或 calc();

正式語法

max-width = 
none |
<length-percentage [0,∞]> |
min-content |
max-content |
fit-content( <length-percentage [0,∞]> ) |
<calc-size()> |
<anchor-size()> |
stretch |
fit-content |
contain

<length-percentage> =
<length> |
<percentage>

<calc-size()> =
calc-size( <calc-size-basis> , <calc-sum> )

<anchor-size()> =
anchor-size( [ <anchor-name> || <anchor-size> ]? , <length-percentage>? )

<calc-size-basis> =
<size-keyword> |
<calc-size()> |
any |
<calc-sum>

<calc-sum> =
<calc-product> [ [ '+' | '-' ] <calc-product> ]*

<anchor-name> =
<dashed-ident>

<anchor-size> =
width |
height |
block |
inline |
self-block |
self-inline

<calc-product> =
<calc-value> [ [ '*' | / ] <calc-value> ]*

<calc-value> =
<number> |
<dimension> |
<percentage> |
<calc-keyword> |
( <calc-sum> )

<calc-keyword> =
e |
pi |
infinity |
-infinity |
NaN

示例

以畫素設定最大寬度

在此示例中,“子元素”的寬度將為 150 畫素或“父元素”的寬度,取兩者中較小的一個。

HTML

html
<div id="parent">
  <div id="child">
    Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis.
  </div>
</div>

CSS

css
#parent {
  background: lightblue;
  width: 300px;
}

#child {
  background: gold;
  width: 100%;
  max-width: 150px;
}

結果

規範

規範
CSS Box Sizing Module Level 4
# sizing-values

瀏覽器相容性

另見