max-width CSS 属性设置元素的最大宽度。它可防止 {{cssxref("width")}} 属性的应用值大于 max-width 指定的值。
{{InteractiveExample("CSS Demo: max-width")}}
```css interactive-example-choice max-width: 150px;
```css interactive-example-choice
max-width: 20em;
```css interactive-example-choice max-width: 75%;
```css interactive-example-choice
max-width: 20ch;
```html interactive-example
Change the maximum width.
```css interactive-example
#example-element {
display: flex;
flex-direction: column;
background-color: #5b6dcd;
height: 80%;
justify-content: center;
color: #ffffff;
}
max-width 会覆盖 {{cssxref("width")}} 的设置,但 {{ Cssxref("min-width") }} 的设置会覆盖 max-width。
语法
/* <length> 值 */
max-width: 3.5em;
/* <percentage> 值 */
max-width: 75%;
/* 关键字值 */
max-width: none;
max-width: max-content;
max-width: min-content;
max-width: fit-content;
max-width: fit-content(20em);
/* 全局值 */
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))。
- : 使用可用空间,但不得超过 max-content,即
fit-content({{cssxref("<length-percentage>")}}){{Experimental_Inline}}- : 使用
fit-content公式,用指定参数替换可用空间,即min(max-content, max(min-content, argument))。
- : 使用
无障碍考虑
确保设置了 max-width 的元素在页面缩放以增大文字大小时不会被截断和/或遮挡其他内容。
形式定义
{{cssinfo}}
形式语法
{{csssyntax}}
示例
设置最大像素宽度
在本例中,“child”的宽度为 150 像素或“parent”的宽度,以较小者为准。
HTML
<div id="parent">
<div id="child">
Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis.
</div>
</div>
CSS
#parent {
background: lightblue;
width: 300px;
}
#child {
background: gold;
width: 100%;
max-width: 150px;
}
{{EmbedLiveSample("设置最大像素宽度", 350, 100)}}