width

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

* Some parts of this feature may have varying levels of support.

width 属性用于设置元素的宽度。width 默认设置内容区域的宽度,但如果 box-sizing 属性被设置为 border-box,就转而设置边框区域的宽度。

尝试一下

width: 150px;
width: 20em;
width: 75%;
width: auto;
This is a box where you can change the width.
#example-element {
  display: flex;
  flex-direction: column;
  background-color: #5b6dcd;
  height: 80%;
  justify-content: center;
  color: #ffffff;
}

min-widthmax-width 属性的优先级高于 width

语法

css
/*  values */
width: 300px;
width: 25em;

/*  value */
width: 75%;

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

/* Global values */
width: inherit;
width: initial;
width: unset;

width 属性也指定为:

使用绝对值定义宽度。

使用外层元素的容纳区块宽度(the containing block's width)的百分比定义宽度。

auto

浏览器将会为指定的元素计算并选择一个宽度。

max-content 实验性

元素内容固有的(intrinsic)合适宽度。

min-content 实验性

元素内容固有的最小宽度。

fit-content 实验性

取以下两种值中的较大值:

  • 固有的最小宽度
  • 固有首选宽度(max-content)和可用宽度(available)两者中的较小值

可表示为:min(max-content, max(min-content, ))

形式语法

width = 
auto |
|
min-content |
max-content |
fit-content( ) |
|


=
|


=
calc-size( , )

=
anchor-size( [ || ]? , ? )

=
|
|
any |


=
[ [ '+' | '-' ] ]*

=


=
width |
height |
block |
inline |
self-block |
self-inline

=
[ [ '*' | / ] ]*

=
|
|
|
|
( )

=
e |
pi |
infinity |
-infinity |
NaN

示例

默认宽度

css
p.goldie {
  background: gold;
}
html

The Mozilla community produces a lot of great software.

像素 px 和字高 em

css
.px_length {
  width: 200px;
  background-color: red;
  color: white;
  border: 1px solid black;
}

.em_length {
  width: 20em;
  background-color: white;
  color: red;
  border: 1px solid black;
}
html
以 px 度量的宽度
以 em 度量的宽度

百分比

css
.percent {
  width: 20%;
  background-color: silver;
  border: 1px solid red;
}
html
按照百分比度量的宽度

max-content 使用示例

css
p.maxgreen {
  background: lightgreen;
  width: intrinsic; /* Safari/WebKit 使用了非标准的名称 */
  width: -moz-max-content; /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}
html

The Mozilla community produces a lot of great software.

min-content 使用示例

css
p.minblue {
  background: lightblue;
  width: -moz-min-content; /* Firefox */
  width: -webkit-min-content; /* Chrome */
}
html

The Mozilla community produces a lot of great software.

无障碍考虑

当页面放大以增加文本大小时,请确保 width 设置的元素不会被截断并且不会遮挡其他内容。

规范

Specification
CSS Box Sizing Module Level 4
# width-height-keywords
CSS Box Sizing Module Level 4
# sizing-values
初始值auto
适用元素all elements but non-replaced inline elements, table rows, and row groups
是否是继承属性
Percentagesrefer to the width of the containing block
计算值a percentage or auto or the absolute length
动画类型a length, percentage or calc();

浏览器兼容性

参见