width
は CSS のプロパティで、要素の幅を設定します。既定では、このプロパティはコンテンツ領域の幅を設定しますが、 box-sizing
を border-box
に設定すると、境界領域の幅を設定します。
このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、 https://github.com/mdn/interactive-examples をクローンしてプルリクエストを送信してください。
構文
/* <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: unset;
width
プロパティは以下のいずれかの値で指定します。
- キーワード値
min-content
,max-content
,fit-content
,auto
のうちの一つ。 <length>
または<percentage>
。
値
<length>
- 絶対的な値で幅を定義します。
<percentage>
- 親となる包含ブロックの幅に対するパーセント値で定義します。
auto
- 指定された要素の幅をブラウザーが計算して決めます。
max-content
- 望ましい固有の幅です。
min-content
- 最小の固有の幅です。
fit-content(
<length-percentage>
)- 利用可能な空間に対して fit-content 式を使用し、指定された引数に置き換えられます。すなわち
min(max-content, max(min-content, <length-percentage>))
です。
アクセシビリティの考慮
ページを拡大してテキストサイズを大きくしたときに、 width
を設定した要素が切り捨てられたり、他のコンテンツが見えなくなったりしないようにしてください。
公式定義
初期値 | auto |
---|---|
適用対象 | all elements but non-replaced inline elements, table rows, and row groups |
継承 | なし |
パーセンテージ | 包含ブロックの幅 |
計算値 | パーセンテージ、auto、絶対的な長さのいずれか |
アニメーションの種類 | length または percentage, calc(); |
形式文法
auto | <length> | <percentage> | min-content | max-content | fit-content(<length-percentage>)where
<length-percentage> = <length> | <percentage>
例
既定の幅
p.goldie {
background: gold;
}
<p class="goldie">The Mozilla community produces a lot of great software.</p>
ピクセル数と em 単位
.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">Width measured in px</div>
<div class="em_length">Width measured in em</div>
パーセント値
.percent {
width: 20%;
background-color: silver;
border: 1px solid red;
}
<div class="percent">Width in percentage</div>
max-content
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;
}
<p class="maxgreen">The Mozilla community produces a lot of great software.</p>
min-content
p.minblue {
background: lightblue;
width: -moz-min-content; /* Firefox */
width: -webkit-min-content; /* Chrome */
width: min-content;
}
<p class="minblue">The Mozilla community produces a lot of great software.</p>
仕様書
仕様書 | 状態 | 備考 |
---|---|---|
CSS Box Sizing Module Level 4 width の定義 |
編集者草案 | |
CSS Box Sizing Module Level 3 width の定義 |
草案 | キーワード max-content , min-content ,
|
CSS Level 2 (Revision 1) width の定義 |
勧告 | 適用対象の要素を詳しく記載 |
CSS Level 1 width の定義 |
勧告 | 初回定義 |
ブラウザーの互換性
BCD tables only load in the browser
このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 https://github.com/mdn/browser-compat-data をチェックアウトしてプルリクエストを送信してください。
関連情報
- ボックスモデル
height
box-sizing
min-width
,max-width
- 対応する論理的プロパティ:
block-size
,inline-size