fit-content

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2021.

fit-content キーワードは fit-content(stretch) と同等です。実際には、ボックスは利用可能な空間を使用しますが、 max-content 以上にはならないことを意味します。

width, height, min-width, min-height, max-width, max-height のレイアウトされたボックスの大きさとして使用される場合、最大寸法と最小寸法は、コンテンツの寸法を参照します。

interpolate-size プロパティと calc-size() 関数を使用して、 fit-content との間でアニメーションをすることができます。

メモ: CSS ボックスサイズ指定の仕様書では、 fit-content() という関数も定義されています。このページではキーワード版について詳しく説明します。

構文

css
width: fit-content;
block-size: fit-content;

fit-content を使用してボックスの大きさを指定

HTML

html
<div class="container">
  <div class="item">アイテム</div>
  <div class="item">もっとテキストの多いアイテム。</div>
  <div class="item">
    テキストを多く持つアイテム。できるだけ多くのテキストを追加したので、テキストが折り返し始めることを期待しています。
  </div>
</div>

CSS

css
.container {
  border: 2px solid #ccc;
  padding: 10px;
  width: 20em;
}

.item {
  width: fit-content;
  background-color: #8ca0ff;
  padding: 5px;
  margin-bottom: 1em;
}

結果

仕様書

Specification
CSS Box Sizing Module Level 4
# valdef-width-fit-content

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
fit-content

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Uses a non-standard name.
Requires a vendor prefix or different name for use.
Has more compatibility info.

関連情報