width

width は CSS のプロパティで、要素の幅を設定します。既定では、このプロパティはコンテンツ領域の幅を設定しますが、 box-sizingborder-box に設定すると、境界領域の幅を設定します。

試してみましょう

width に指定された値は、その値が min-width および max-width で定義された値内にある限り、コンテンツ領域に適用されます。

  • width の値が min-width の値より小さい場合、min-widthwidth をオーバーライドします。
  • width の値が max-width の値より大きい場合、max-widthwidth をオーバーライドします。

構文

css
/* <length> 値 */
width: 300px;
width: 25em;

/* <percentage> 値 */
width: 75%;

/* キーワード値 */
width: max-content;
width: min-content;
width: fit-content;
width: fit-content(20em);
width: auto;

/* グローバル値 */
width: inherit;
width: initial;
width: revert;
width: revert-layer;
width: unset;

<length>

絶対的な値で幅を定義します。

<percentage>

親となる包含ブロックの幅に対するパーセント値で定義します。

auto

指定された要素の幅をブラウザーが計算して決めます。

max-content

望ましい固有の幅です。

min-content

最小の固有の幅です。

fit-content

利用可能なスペースを使用しますが、max-content、つまり min(max-content, max(min-content, stretch)) を超えません。

fit-content(<length-percentage>) Experimental

利用可能な空間に対して fit-content 式を使用し、指定された引数に置き換えられます。すなわち min(max-content, max(min-content, <length-percentage>)) です。

アクセシビリティの考慮

ページを拡大してテキストサイズを大きくしたときに、 width を設定した要素が切り捨てられたり、他のコンテンツが見えなくなったりしないようにしてください。

公式定義

初期値auto
適用対象置換要素でないインライン要素、テーブルの行、行グループを除くすべての要素
継承なし
パーセント値包含ブロックの幅に対する相対値
計算値パーセント値、 auto、絶対的な長さのいずれか
アニメーションの種類length または パーセント値, calc();

形式文法

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>

Percentage の例

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
CSS Box Sizing Module Level 4
# sizing-values

ブラウザーの互換性

BCD tables only load in the browser

関連情報