width
width
は CSS のプロパティで、要素の幅を設定します。既定では、このプロパティはコンテンツ領域の幅を設定しますが、 box-sizing
を border-box
に設定すると、境界領域の幅を設定します。
試してみましょう
構文
css
/* <length> 値 */
width: 300px;
width: 25em;
/* <percentage> 値 */
width: 75%;
/* キーワード値 */
width: max-content;
width: min-content;
width: fit-content(20em);
width: auto;
/* グローバル値 */
width: inherit;
width: initial;
width: revert;
width: unset;
値
<length>
-
絶対的な値で幅を定義します。
<percentage>
-
親となる包含ブロックの幅に対するパーセント値で定義します。
auto
-
指定された要素の幅をブラウザーが計算して決めます。
max-content
-
望ましい固有の幅です。
min-content
-
最小の固有の幅です。
fit-content(
<length-percentage>
)-
利用可能な空間に対して fit-content 式を使用し、指定された引数に置き換えられます。すなわち
min(max-content, max(min-content, <length-percentage>))
です。
アクセシビリティの考慮
ページを拡大してテキストサイズを大きくしたときに、 width
を設定した要素が切り捨てられたり、他のコンテンツが見えなくなったりしないようにしてください。
公式定義
形式文法
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>
ピクセル数と 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">Width measured in px</div>
<div class="em_length">Width measured in em</div>
パーセント値
css
.percent {
width: 20%;
background-color: silver;
border: 1px solid red;
}
html
<div class="percent">Width in percentage</div>
max-content
css
p.maxgreen {
background: lightgreen;
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
width: max-content;
}
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 */
width: min-content;
}
html
<p class="minblue">The Mozilla community produces a lot of great software.</p>
仕様書
Specification |
---|
CSS Box Sizing Module Level 4 # width-height-keywords |
ブラウザーの互換性
BCD tables only load in the browser
関連情報
- ボックスモデル
height
box-sizing
min-width
,max-width
- 対応する論理的プロパティ:
block-size
,inline-size