fit-content

fit-contentfit-content(stretch) として動作します。実際には、ボックスは利用可能な空間を使用しますが、 max-content 以上にはならないことを意味します。

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

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

構文

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

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

HTML

html
<div class="container">
  <div class="item">Item</div>
  <div class="item">Item with more text in it.</div>
  <div class="item">
    Item with more text in it, hopefully we have added enough text so the text
    will start to wrap.
  </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

ブラウザーの互換性

BCD tables only load in the browser

関連情報