📜  CSS Grid 中的 Auto-Fit 与 Auto-Fill 属性

📅  最后修改于: 2022-05-13 01:56:52.276000             🧑  作者: Mango

CSS Grid 中的 Auto-Fit 与 Auto-Fill 属性

CSS Grid 中最重要的特性之一是我们可以在不使用媒体查询的情况下创建响应式布局。我们不需要为每个视口编写媒体查询,而是可以通过使用 CSS-Grid 的一些属性来调整它。它可以通过简单地使用 grid-template-columns 属性、repeat()函数以及 auto-fit 和 auto-fill 关键字来调整。

先决条件:

  • 网格模板列
  • fr 和 repeat() 单元

1. 自动填充:自动填充属性用尽可能多的列填充行。新添加的列可能为空,但仍会占用给定行中的空间。这是 CSS 网格中的一个重要属性,它可以在不为每个网格编写媒体查询的情况下进行响应式布局。

句法:

:auto-fill

例子:

HTML


 

    
    
    
 
    

 

    
        
            

1

        
        
            

2

        
        
            

3

        
        
            

4

        
    
 


HTML


 

    
    
    
 
    
 
    Document

 

    
        
            

1

        
        
            

2

        
        
            

3

        
        
            

4

        
    
 


输出:

自动填充属性图 1

正如我们在图(图 1)中看到的那样,自动填充会自动调整大小并留出可用空间以在其中添加新项目。

2. Auto-fit: Auto-fit 的行为与 auto-fill 相同,但 auto-fit 属性通过扩大其大小以根据设备宽度占用可用空间来填充当前可用空间。如果所有网格项都为空,则将其视为大小为 0px 的单个轨道。

为了找到自动重复轨道的数量,我们需要将轨道大小保持在一个指定的值(例如,1px),以避免被零除。

句法:

:auto-fit

例子:

HTML



 

    
    
    
 
    
 
    Document

 

    
        
            

1

        
        
            

2

        
        
            

3

        
        
            

4

        
    
 

输出:

自动适应属性(图 2)

自动填充和自动拟合之间的区别如下:

Auto-fill

Auto-fit

The browser will allow empty columns to occupy space in a row.The content will stretch to fill the entire row width.
Grid layout remains fixed with or without items.Grid layout is not fixed ,the content stretch to fit entire width.
Shifting of items in a grid is possible as there are vacant space in a row.Shifting of items in a grid is not  possible.