width
width 属性用于设置元素的宽度。width 默认设置内容区域的宽度,但如果 box-sizing 属性被设置为 border-box,就转而设置边框区域的宽度。
尝试一下
语法
css
/* <length> values */
width: 300px;
width: 25em;
/* <percentage> 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 属性也指定为:
- 下面关键字值之一:
min-content,max-content,fit-content,auto。 - 一个长度值
<length>或者百分比值<percentage>。
值
<length>-
使用绝对值定义宽度。
<percentage>-
使用外层元素的容纳区块宽度(the containing block's width)的百分比定义宽度。
auto-
浏览器将会为指定的元素计算并选择一个宽度。
max-content实验性-
元素内容固有的(intrinsic)合适宽度。
min-content实验性-
元素内容固有的最小宽度。
fit-content实验性-
取以下两种值中的较大值:
- 固有的最小宽度
- 固有首选宽度(max-content)和可用宽度(available)两者中的较小值
可表示为:
min(max-content, max(min-content, <length-percentage>))
形式语法
width =
auto |
<length-percentage [0,∞]> |
min-content |
max-content |
fit-content( <length-percentage [0,∞]> )
<length-percentage> =
<length> |
<percentage>
示例
默认宽度
css
p.goldie {
background: gold;
}
html
<p class="goldie">The Mozilla community produces a lot of great software.</p>
像素 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
<div class="px_length">以 px 度量的宽度</div>
<div class="em_length">以 em 度量的宽度</div>
百分比
css
.percent {
width: 20%;
background-color: silver;
border: 1px solid red;
}
html
<div class="percent">按照百分比度量的宽度</div>
max-content 使用示例
css
p.maxgreen {
background: lightgreen;
width: intrinsic; /* Safari/WebKit 使用了非标准的名称 */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
html
<p class="maxgreen">The Mozilla community produces a lot of great software.</p>
min-content 使用示例
css
p.minblue {
background: lightblue;
width: -moz-min-content; /* Firefox */
width: -webkit-min-content; /* Chrome */
}
html
<p class="minblue">The Mozilla community produces a lot of great software.</p>
无障碍考虑
当页面放大以增加文本大小时,请确保 width 设置的元素不会被截断并且不会遮挡其他内容。
规范
| Specification |
|---|
| CSS Box Sizing Module Level 4 # width-height-keywords |
| 初始值 | auto |
|---|---|
| 适用元素 | all elements but non-replaced inline elements, table rows, and row groups |
| 是否是继承属性 | 否 |
| Percentages | refer to the width of the containing block |
| 计算值 | a percentage or auto or the absolute length |
| Animation type | a length, percentage or calc(); |
浏览器兼容性
BCD tables only load in the browser