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

浏览器兼容性

另见