width

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

試してみましょう

min-width および max-width プロパティは width を上書きします。

構文

/* <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 を設定した要素が切り捨てられたり、他のコンテンツが見えなくなったりしないようにしてください。

公式定義

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

形式文法

width = 
auto |
<length-percentage [0,∞]> |
min-content |
max-content |
fit-content( <length-percentage [0,∞]> )

<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>

仕様書

Specification
CSS Box Sizing Module Level 4
# width-height-keywords

ブラウザーの互換性

BCD tables only load in the browser

関連情報