元素宽度 width
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 属性可以指定为:
- 一个长度值
<length>或者百分比值<percentage>。 - 下面关键字值之一:
min-content,max-content,fit-content,auto。
技巧
在实际开发中,我们在调试盒子模型的时候,可以通过设置 background-color 背景颜色属性来辅助调试,这样就可以很清楚的看到盒子模型的各个区域了。在调试正常后,再把 background-color 属性去掉。
取值
<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>
规范

示例
- HTML
- CSS
<div class="css-content-box-width-demo">
<div class="auto">width: auto;</div>
<div class="px">width: 150px;</div>
<div class="em">width: 12.5em;</div>
<div class="percent">width: 75%;</div>
<div class="max-content">width: max-content;</div>
<div class="min-content">width: min-content;</div>
<div class="fit-content">width: fit-content(20em);</div>
</div>
.css-content-box-width-demo {
padding: 10px 20px;
font: bold 16px/1.5 sans-serif;
}
.css-content-box-width-demo > div {
margin-top: 5px;
background-color: rgb(128, 164, 149);
border-radius: 5px;
}
.css-content-box-width-demo > div.auto {
width: auto;
}
.css-content-box-width-demo > div.px {
width: 150px;
}
.css-content-box-width-demo > div.em {
width: 12.5em;
}
.css-content-box-width-demo > div.percent {
width: 75%;
}
.css-content-box-width-demo > div.max-content {
width: max-content;
}
.css-content-box-width-demo > div.min-content {
width: min-content;
}
.css-content-box-width-demo > div.fit-content {
width: fit-content(20em);
}
http://localhost:3000/css-content-box-width-demo.html
width: auto;
width: 150px;
width: 12.5em;
width: 75%;
width: max-content;
width: min-content;
width: fit-content(20em);