--- title: width slug: Web/CSS/width tags: - CSS - 参考 - 大小 - 宽度 translation_of: Web/CSS/width ---
width
属性用于设置元素的宽度。width
默认设置内容区域的宽度,但如果 {{cssxref("box-sizing")}} 属性被设置为 border-box
,就转而设置边框区域的宽度。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
{{ cssxref("min-width") }} 和 {{ cssxref("max-width") }} 属性的优先级高于 {{ cssxref("width") }}。
/* <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>
。auto
max-content
{{ experimental_inline }}min-content
{{ experimental_inline }}fit-content
{{ experimental_inline }}min(max-content, max(min-content, <length-percentage>))
{{csssyntax}}
p.goldie { background: gold; }
<p class="goldie">The Mozilla community produces a lot of great software.</p>
{{EmbedLiveSample('Default_width', '500px', '64px')}}
.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; }
<div class="px_length">以 px 度量的宽度</div> <div class="em_length">以 em 度量的宽度</div>
{{EmbedLiveSample('Pixels_and_ems', '500px', '64px')}}
.percent { width: 20%; background-color: silver; border: 1px solid red; }
<div class="percent">按照百分比度量的宽度</div>
{{EmbedLiveSample('百分比', '500px', '64px')}}
max-content
p.maxgreen { background: lightgreen; width: intrinsic; /* Safari/WebKit 使用了非标准的名称 */ width: -moz-max-content; /* Firefox/Gecko */ width: -webkit-max-content; /* Chrome */ }
<p class="maxgreen">The Mozilla community produces a lot of great software.</p>
{{EmbedLiveSample('max-content', '500px', '64px')}}
min-content
p.minblue { background: lightblue; width: -moz-min-content; /* Firefox */ width: -webkit-min-content; /* Chrome */ }
<p class="minblue">The Mozilla community produces a lot of great software.</p>
{{EmbedLiveSample('min-content', '500px', '155px')}}
当页面放大以增加文本大小时,请确保 width
设置的元素不会被截断并且不会遮挡其他内容。
规范 | 状态 | 注释 |
---|---|---|
{{ SpecName('CSS3 Box', '#the-width-and-height-properties', 'width') }} | {{Spec2('CSS3 Box')}} | 增加 max-content , min-content , available , fit-content , border-box , content-box 关键字。 |
{{ SpecName('CSS2.1', 'visudet.html#the-width-property', 'width') }} | {{Spec2('CSS2.1')}} | 明确了此属性对哪些元素有效。 |
{{ SpecName('CSS1', '#width', 'width') }} | {{Spec2('CSS1')}} | 初始定义。 |
{{cssinfo}}
{{Compat("css.properties.width")}}
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.