CSS 网格中自动调整 (Auto-fit) 与自动填充 (Auto-fill) 属性的区别

cssweb developmentfront end technology更新于 2024/10/31 3:24:17

响应式网页是开发网站时必须始终牢记的关键点。网格模块使开发人员能够轻松设计网页,而无需进行大量定位,因为 id 模块提供了一个包含行和列的网格类型布局系统。

自动填充 (Auto-fill) 属性

自动填充 (Auto-fill) 属性用于使用可能的列填充行,添加的列将占用空间,而另一列将为空。自动填充 (Auto-fill) 属性是 CSS 网格的一个重要属性,主要用于在不使用媒体查询的情况下创建响应式布局。

语法

让我们来看看自动填充 (Auto-fill) 属性的语法。

:auto-fill;

示例

在下面的程序中,

  • 我们首先创建了一个"autofill"类,然后在该类中放置了3个项目,每个项目都用不同的颜色填充不同的框。

  • 我们将"display"属性设置为 grid,并为容器分配了高度和宽度。之后,使用 auto-fill 属性设置其最小最大值。

  • 最后,我们为之前创建的3个项目设置了尺寸。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Example of using the auto-fill property</title>
   <style>
      .first-item {
         background-color: violet;
         border: solid black 4px ;
         max-width: 100%;
         min-height: 150px;
         height: auto;
      }
      .second-item {
         background-color: blue;
         border: solid black 5px;
         min-height: 150px;
         max-width: 100%;
         height: auto;
      }
      .third-item {
         background-color: maroon;
         border: solid black 5px;
         min-height: 150px;
         max-width: 100%;
         height: auto;
      }
      .autfill {
         margin-top: 4%;
         border: solid black 3px;
         width: 80vh;
         grid-template-columns: repeat(
         auto-fill, minmax(190px, 1fr));
         display: grid;
         gap: 5px;
      }
      .para{
         text-align: center;
      }
   </style>
</head>
<body>
   <div class="content">
      <div class="para"><h1>This is an example!!</h1></div>
      <div class="autfill">
         <div class="first-item"><h2 class="group">1</h1></div>
         <div class="second-item"><h2 class="group">2</h1></div>
         <div class="third-item"><h2 class="group">3</h1></div>
      </div>
   </div>
</body>
</html>

自动调整属性

"自动调整"属性与"自动填充"属性类似,唯一的区别在于,该属性会根据设备的宽度,通过占用可用空间来扩展其大小。如果网格中的所有项目都为空,则所有项目都将被视为单个轨道。

示例

在下面的示例中,我们将属性值设置为自动调整。自动调整属性将自行拉伸,以填充整行的宽度,并通过拉伸填充任何空白处。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Example of using the auto-fit property</title>
   <style>
      #container {
         display:grid;
         width:100%;
         border:2px solid blue;
         grid-template-columns: repeat(auto-fit, minmax(100px, 2fr));
      }
      #first-item,#second-item,#third-item {
         height:100px;
         margin:3px 15px 15px 2px;
         background-color: blue;
      }
   </style>
</head>
<body>
   <div id="container">
      <div id="first-item">1</div>
      <div id="second-item">2</div>
      <div id="third-item">3</div>
   </div>
</body>
<html>

在上面的例子中,您可以看到项目已经填满了行的整个宽度以及剩余空间的区域。

自动调整与自动填充属性

网格布局具有不同的属性。自动调整和自动填充属性都是 CSS 网格模块的一部分。网格布局的语法如下:

.container-grid{
    display: grid;
}

以上是网格布局的语法,它将 HTML 元素的 display 属性设置为网格布局。

结论

自动调整和自动填充都是 CSS 网格的属性,用于创建响应式布局,而无需使用媒体查询。其中,自动填充属性允许行中出现空白,而自动调整属性则允许内容自行拉伸,直至完全填满整行。在本文中,我们介绍了用于创建响应式布局的两个属性"自动填充"和"自动调整"。


相关文章


有用资源