CSS 函式 - fit-content()



CSS 函式 fit-content() 使用公式 min(最大尺寸, max(最小尺寸, 引數)) 來限制給定尺寸在一個由最小和最大尺寸確定的範圍內。

  • CSS 網格 中,fit-content() 函式可用作軌道尺寸。

    在這種情況下,它使用 auto 來確定 最小尺寸max-content 來確定最大尺寸,這類似於計算 minmax(auto, max-content)

  • fit-content() 函式充當 widthheightmin-widthmin-heightmax-widthmax-height 的盒子尺寸指定符。

    在此用法中,最大和最小尺寸由內容的尺寸確定。

可能的值

引數 <length><percentage> 可以傳遞給 fit-content() 函式。

  • <length> - 絕對長度。

  • <percentage> - 在給定的軸上,百分比相對於可用空間計算。

    它與網格容器中行軌道的塊級尺寸和列軌道的內聯尺寸相關。

    在網格引數之外,它取決於書寫模式以及已佈局盒子的可用內聯或塊級尺寸。

語法

fit-content: length | percentage 

CSS fit-content() - <length> 值

在以下示例中,grid-template-columns 被賦予 CSS 屬性 fit-content(),這使得列能夠根據內容調整大小,並在 #custom-container 網格內的每列中設定最大寬度。

<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-container 的 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>
廣告

© . All rights reserved.