width
width 属性用于设置元素的宽度。默认设置内容区域的宽度。但如果
box-sizing
属性被设置为
border-box
,就转而设置边框区域的宽度。
示例
/* <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
|
||||
语法
width : auto | <length> | <percentage> | min-content | max-content | fit-content()
width 属性也指定为:
- 下面关键字值之一:min-content,max-content,fit-content,auto。
-
一个长度值
或者百分比值 。
取值:
- auto :浏览器将会为指定的元素计算并选择一个宽度。
-
<length>
:使用绝对值定义宽度。参见
<length>。 -
<percentage>
:使用外层元素的容纳区块宽度(the containing block's width)的百分比定义宽度。参见
<percentage>。 - min-content :元素内容固有的(intrinsic)合适宽度。 还处于实验阶段
- max-content :元素内容固有的最小宽度 还处于实验阶段 。
-
fit-content()
:
还处于实验阶段
.取以下两种值中的较大值:
- 固有的最小宽度
- 固有首选宽度(max-content)和可用宽度(available)两者中的较小值
-
可表示为:min(max-content, max(min-content,
))。
| 默认值 | auto |
| 适用于 | 除未替换的内联元素、表行和行组之外的所有元素 |
| 继承性 | 无 |
| 动画性 | 否 |
| 计算值 | 指定值 |
实例
.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;
}
.percent {
width: 20%;
background-color: silver;
border: 1px solid red;
}
p.maxgreen {
background: lightgreen;
width: intrinsic; /* Safari/WebKit 使用了非标准的名称 */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
p.minblue {
background: lightblue;
width: -moz-min-content; /* Firefox */
width: -webkit-min-content; /* Chrome */
}