fit-content() - CSS: Cascading Style Sheets 编辑

The fit-content() CSS function clamps a given size to an available size according to the formula min(maximum size, max(minimum size, argument)).

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

The function can be used as a track size in CSS Grid properties, where the maximum size is defined by max-content and the minimum size by auto, which is calculated similar to auto (i.e., minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum.

The function can also be used as laid out box size for width, height, min-width, min-height, max-width and max-height, where the maximum and minimum sizes refer to the content size.

Syntax

The fit-content() function accepts a <length> or a <percentage> as an argument.

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

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

Values

<length>
An absolute length.
<percentage>
A percentage relative to the available space in the given axis.
In grid properties it is relative to the inline size of the grid container in column tracks and to the block size of the grid container for row tracks. Otherwise it is relative to the available inline size or block size of the laid out box depending on the writing mode.

Examples

Sizing grid columns with fit-content

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

#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;
}

Result

Specifications

SpecificationStatusComment
CSS Box Sizing Module Level 3
The definition of 'fit-content()' in that specification.
Working DraftDefines the function as laid out box size for width, height, min-width, min-height, max-width and max-height.
CSS Grid Layout
The definition of 'fit-content()' in that specification.
Candidate RecommendationDefines the function when used as a track size.

Browser compatibility

Supported in grid layout

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:120 次

字数:7776

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文