fit-content()

fit-content() CSS 函数根据公式 min(最大尺寸, max(最小尺寸, 参数)) 将给定尺寸限制在可用尺寸内。

试一试

grid-template-columns: fit-content(8ch) fit-content(8ch) 1fr;
grid-template-columns: fit-content(100px) fit-content(100px) 1fr;
grid-template-columns: fit-content(40%) fit-content(40%) 1fr;
<section class="default-example" id="default-example">
  <div class="example-container">
    <div class="transition-all" id="example-element">
      <div>One. This column has more text in it.</div>
      <div>Two</div>
      <div>Three</div>
      <div>Four</div>
      <div>Five</div>
    </div>
  </div>
</section>
#example-element {
  border: 1px solid #c5c5c5;
  display: grid;
  grid-gap: 10px;
  width: 250px;
}

#example-element > div {
  background-color: rgb(0 0 255 / 0.2);
  border: 3px solid blue;
  text-align: left;
}

该函数可以用作 CSS Grid 属性中的轨道尺寸,其中最大尺寸由 max-content 定义,最小尺寸由 auto 定义,其计算方式类似于 auto(即 minmax(auto, max-content)),但如果轨道尺寸大于 auto 的最小尺寸,则会将其限制在 *参数* 值。

有关 max-contentauto 关键字的更多信息,请参阅 grid-template-columns 页面。

fit-content() 函数还可以用作 widthheightmin-widthmin-heightmax-widthmax-height 的布局框尺寸,其中最大尺寸和最小尺寸指的是内容尺寸。

语法

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

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

<length>

一个绝对长度。

<percentage>

相对于给定轴上可用空间的百分比。

在网格属性中,它相对于列轨道中网格容器的内联尺寸,以及行轨道中网格容器的块尺寸。否则,它相对于布局框的可用内联尺寸或块尺寸,具体取决于书写模式。

正式语法

<fit-content()> = 
fit-content( <length-percentage [0,∞]> )

<length-percentage> =
<length> |
<percentage>

示例

使用 fit-content 调整网格列大小

HTML

html
<div id="container">
  <div>Item as wide as the content.</div>
  <div>
    Item with more text in it. Because the contents of it are wider than the
    maximum width, it is clamped at 300 pixels.
  </div>
  <div>Flexible item</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;
}

结果

规范

规范
CSS 网格布局模块 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

css.properties.width.fit-content_function

另见