fit-content()

fit-content()CSS関数で、指定された寸法を min(最大サイズ, max(最小サイズ, 引数)) の式に従って有効な範囲の寸法に収めます。

試してみましょう

この関数は CSS グリッドのプロパティにおいて、トラックの寸法を max-content で定義された最大寸法と auto で定義された最小寸法との間で、 auto と似た方法(すなわち minmax(auto, max-content))で計算しますが、 auto の最小値よりも大きい場合は引数がトラックの寸法になるという点が異なります。

max-content および auto キーワードについての詳細は、 grid-template-columns ページを参照してください。

fit-content() 関数は width, height, min-width, min-height, max-width, max-height のレイアウトボックスの寸法としても使用され、最大寸法は内容物の最大寸法、最小寸法は内容物の最小寸法になります。

構文

引数として <length> または <percentage> を受け付ける関数です。

css
/* <length> 値 */
fit-content(200px)
fit-content(5cm)
fit-content(30vw)
fit-content(100ch)

/* <percentage> 値 */
fit-content(40%)

<length>

絶対的な長さです。

<percentage>

指定された軸で有効な空間に対する相対的なパーセント値です。

グリッドプロパティでは、行トラックにおける列内のグリッドコンテナーのインライン方向の寸法およびグリッドコンテナーのブロック方向の寸法の相対値です。それ以外では、書字方向に応じてレイアウトボックスの有効なインライン方向の寸法またはブロック方向の寸法に対する相対値になります。

グリッドカラムの大きさを fit-content で指定

HTML

html
<div id="container">
  <div>コンテンツの幅のアイテム。</div>
  <div>
    テキストが多いアイテムです。コンテンツが最大幅より広いため、 300 ピクセルで固定されています。
  </div>
  <div>柔軟なアイテム</div>
</div>

CSS

css
#container {
  display: grid;
  grid-template-columns: fit-content(300px) fit-content(300px) 1fr;
  grid-gap: 5px;
  box-sizing: border-box;
  height: 200px;
  width: 100%;
  background-color: #8cffa0;
  padding: 10px;
}

#container > div {
  background-color: #8ca0ff;
  padding: 5px;
}

結果

仕様書

Specification
CSS Grid Layout Module Level 2
# funcdef-grid-template-columns-fit-content
CSS Box Sizing Module Level 3
# funcdef-width-fit-content

ブラウザーの互換性

css.properties.grid-template-columns.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

css.properties.width.fit-content_function

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()
Experimental

Legend

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

No support
No support
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.

関連情報