Grid布局基础知识

Wenn 于 2022-09-07 发布

Grid布局

/*不设置容器的大小*/
display: grid;
grid-template-columns: repeat(auto-fill, 300px); /*定义子盒子(项目)宽度为300px排序,按照容器的宽度自动排列,当用户缩放窗口时会自动向上一行排列*/

此时右上角的容器宽度小于300px,当右上角的宽度大于300px时,项目5就会自动排列到项目4旁边,如果项目1-4之间的宽度小于4*300px;则项目四会排列到下面项目5的位置,项目5则移动到项目6的位置,依次类推;

display: grid;
grid-template-columns: repeat(3, 1fr); /*将容器的宽均分为3份,各占一份*/
grid-template-columns: 1fr 2fr 3fr; /*将容器的款分为6份,其中第一个为1份,第二个2份,第三个3份*/

display: grid;
grid-template-columns: 1fr minmax(400px, 1fr); /*此时设置第一列的宽均分容器的一半,第二列的宽为最低400px,最高与第一列均分容器的宽度,当容器的宽度缩小为800px以下时,仅仅会压缩第一列的宽度,第二列的宽度将会一直是400px*/

image-20220907111729371

dislay: grid;
grid-template-columns: 100px auto 100px; /*定义左右两侧列固定宽度为100px,中间列宽度=容器宽-(左列宽+右列宽)*/


display: grid;
grid-template-columns: repeat(3,100px);
gap: 100px; /*设置子项目之间的间距为100px,等同于下面的两句*/

row-gap: 100px;
column: 100px;

display:grid;
grid-template-colmuns: repeat(3,100px);
grid-template-rows: repeat(4,100px);
grid-auto-flow: row; /*默认值,按照行排列*/
grid-auto-flow: column; /*修改为按照列排列*/

display: grid;
grid-template-columns: repeat(3,100px);
grid-template-rows: repeat(4,100px);
place-items: center; /*这一句与下面两句的结合作用相同*/

justify-items: center;/*子项目内容水平居中*/
aligin-items: center; /*子项目内容垂直居中*/

display: grid;
grid-template-colmuns: repeat(3,100px);
grid-template-rows: repeat(3,100px);
grid-auto-rows: 50px; 
/*定义了一个3行3列的布局,但实际有10个盒子,这样在行多出来的盒子将以50px的高度排列;如果是列的话,将以对应的宽度排列*/


项目属性

/*写在子项目(子盒子)上*/
grid-colmun: 1 / 4; /*从第一个线开始,从第4根线结束;与下面两行的设置作用相同*/

grid-colmun-start: 1;
grid-colmun-end: 4;

grid-colmun: 1 / 3; 
grid-row: 1 / 3; /*设置子盒子的高从第一行开始,到第3行结束*/

grid-colmun: span 2;
grid-row: span 2; /*与上面的的数字设置样式设置相同*/

grid-area: 1 / 1 / 3 / 3; /*甚至我们可以使用这样来设置*/

当出现以上这种情况时,我们对于该容器的利用率并不高,所以我们就要使空余部分以其他的盒子进行填充,代码如下:

grid-auto-flow: dense;

/*首先我们需要在父容器上设置盒子区域,归属*/
display: grid;
grid-template-areas:'a a a' 'b b b' 'c c c'; /*定义下面的3行3列区域,第一行为a,第二行为b,第三行为c*/

/*设置子项目属性值*/
grid-area: a; /*设置该子项目独占标记为a的容器区域*/
grid-area: b / 2; /*设置该子项目移动到容器区域标记为b,且是第二个的位置*/