CSS 函式 - repeat()



CSS 函式 repeat() 用於表示標題列表中重複的部分,這是一種更簡潔的方式來定義大量具有重複模式的列或行。

此函式可在 CSS 網格屬性 grid-template-columnsgrid-template-rows 中使用。

repeat() 函式接受兩個引數

  • 重複次數:第一個引數定義應重複軌道列表的次數。可以使用 1 或更高的整數,或者使用關鍵字 auto-fillauto-fit

  • 軌道:第二個引數選擇要複製的軌道。<track-size><fixed-size> 變數可用於提供一個或多個定義這些軌道的尺寸值。

可能的值

<fixed-size>

可以採用以下幾種形式之一:

<flex> - 使用單位 fr 指示軌道靈活性的尺寸,其值為非負值。

<length> - 正整數長度。

<line-names> - 一個或多個 <custom-ident> 值用空格分隔,並用方括號括起來,例如:[first header-start]

<percentage> - 為列網格軌道提供的 <percentage> 數字基於網格容器的內聯大小,而對於行網格軌道,則基於網格容器的塊大小。如果網格容器的軌道控制其大小,則 <percentage> 被視為 auto

auto - 最大值對應於 max-content。最小值表示網格軌道內網格專案(由 min-width/min-height 定義)的最大最小大小。

auto-fill:自動建立儘可能多的軌道以填充網格容器,而不會導致溢位。這將顯示空軌道和填充軌道。請注意,空軌道是沒有網格專案的列或行。

auto-fit:自動建立儘可能多的軌道以填充網格容器,而不會導致溢位。它將空軌道摺疊為 0px。請注意,空軌道是沒有網格專案的列或行。

max-content - 它指示放置在網格軌道中的網格元素對 max-content 的最大貢獻。

min-content - 它指示網格軌道內網格專案對 min-content 的最大貢獻。

CSS repeat() - 使用 auto-fit 和 minmax()

在以下示例中,CSS 屬性 grid-template-columns 使用 repeat() 函式建立響應式網格佈局。

auto-fit 引數根據可用空間動態調整列數,minmax(200px, 1fr) 指定每列的寬度至少為 200 畫素,但可以按比例增長到可用空間。

<html>
<head>
<style>
   body {
      font-family: 'Arial', sans-serif;
      margin: 20px;
      background-color: #f4f4f4;
      color: #333;
   }
   .container {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
   }
   .grid-item {
      background-color: #3498db; 
      padding: 20px;
      text-align: center;
      color: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
   }
   @media (max-width: 600px) {
      .container {
         grid-template-columns: repeat(1, 1fr);
      }
   }
   @media (min-width: 601px) and (max-width: 900px) {
      .container {
         grid-template-columns: repeat(2, 1fr);
      }
   }
   @media (min-width: 901px) and (max-width: 1200px) {
      .container {
         grid-template-columns: repeat(3, 1fr);
      }
   }
   @media (min-width: 1201px) {
      .container {
         grid-template-columns: repeat(4, 1fr);
      }
   }
</style>
</head>
<body>
<div class="container">
   <div class="grid-item">Item 1</div>
   <div class="grid-item">Item 2</div>
   <div class="grid-item">Item 3</div>
   <div class="grid-item">Item 4</div>
   <div class="grid-item">Item 5</div>
   <div class="grid-item">Item 6</div>
   <div class="grid-item">Item 7</div>
   <div class="grid-item">Item 8</div>
   <div class="grid-item">Item 9</div>
   <div class="grid-item">Item 10</div> 
</div>
</body>
</html>
廣告
© . All rights reserved.