CSS 函数 fit-content() 使用公式 min(maximum size, max(minimum size, argument)) 将给定大小限制在由最小和最大大小确定的范围内。
- 在 CSS Grid 中,fit-content() 函数可以用作轨道大小。在本例中,它使用 auto 来确定最小大小,并使用 max-content 来确定最大大小,其计算方式类似于 minmax(auto, max-content)。
- fit-content() 函数用作宽度、高度、最小宽度、最小宽度、最大宽度和最大高度的框大小说明符。此用法中的最大和最小大小由内容的大小确定。
可能的值
参数 <length> 和 <percentage> 可以传递给 fit-content() 函数。
- <length> - 绝对长度。
- <percentage> - 在给定轴上,百分比是相对于可用空间计算的。它与网格属性中行轨道的块大小和网格容器内列轨道的内联大小有关。除了网格参数之外,它还取决于写入模式和布局框的可用内联或块大小。
语法
fit-content: length | percentage
CSS fit-content() - <length>值
在以下示例中,为 grid-template-columns 提供了 CSS 属性 fit-content(),该属性使列能够根据内容调整大小,并为 #custom 容器网格内的每一列设置最大宽度。
<html>
<head>
<style>
#custom-container {
display: grid;
grid-template-columns: fit-content(200px) fit-content(400px) fit-content(200px);
grid-gap: 10px;
box-sizing: border-box;
height: 250px;
width: 80%;
margin: 20px auto;
background-color: #c43b31;
padding: 20px;
}
#custom-container > div {
background-color: #ffd700;
padding: 15px;
}
</style>
</head>
<body>
<div id="custom-container">
<div>Unique Item</div>
<div>A longer description goes here. It might contain more details and interesting information that extends beyond the usual width.</div>
<div>Adaptable Element</div>
</div>
</body>
</html>
CSS fit-content() - <percentage>值
在以下示例中,CSS 属性 fit-content() 应用于 #custom 容器的 grid-template-columns。
它指定了列宽的百分比,使列能够根据容器宽度的相对百分比动态调整大小,最后一列 (1.2fr) 占用剩余空间。
<html>
<head>
<style>
#custom-container {
display: grid;
grid-template-columns: fit-content(20%) fit-content(30%) fit-content(40px) 1.2fr;
grid-gap: 15px;
box-sizing: border-box;
height: 40%;
width: 100%;
background-color: #7b4a93;
padding: 15px;
}
.custom-box {
background-color: #ecf0f1;
padding: 8px;
}
</style>
</head>
<body>
<div id="custom-container">
<div class="custom-box">
Explore new ideas within width.</div>
<div class="custom-box">
Dive into content-rich experiences up to 280px.</div>
<div class="custom-box">
<b>Immerse in knowledge.</b>
Learn about various topics from science to art.</div>
<div class="custom-box">
Responsive to screen size and other divisions' width.</div>
</div>
</body>
</html>