如果想要把某个HTML元素当作Grid容器,将其display属性设置成grid或inline-grid即可。Grid容器的直接子元素则自动成为Grid项,Grid项会被放在Grid容器的行列中。
grid-template-columns属性定义grid容器内有多少列且每列宽度如何。有多少列,该属性就有多少个取值,每个取值是用来定义每一列的宽度如何;不同的值之间使用空格分开。如下所示,该grid容器设置了4列,每一列的宽度取值auto,当然也可以直接设置成具体的像素数值,如下两例所示。
案例1:4列宽度都取值auto
.grid-container {
display: grid;
grid-template-columns: auto auto auto auto;
}
案例2:4列宽度分别取值具体的像素数值
.grid-container {
display: grid;
grid-template-columns: 80px 160px auto 40px;
}
grid-template-rows属性定义grid容器内每行高度如何。
.grid-container {
display: grid;
grid-template-columns: auto auto auto auto;
grid-template-rows: 120px 240px;
}
通过设置justify-content属性,可以定义grid项在grid容器中的水平对齐方式。
案例1:取值space-evenly
.grid-container {
display: grid;
justify-content: space-evenly;
}
案例2:取值space-around
.grid-container {
display: grid;
justify-content: space-around;
}
案例3:取值space-between
.grid-container {
display: grid;
justify-content: space-between;
}
案例4:取值center
.grid-container {
display: grid;
justify-content: center;
}
案例5:取值start
.grid-container {
display: grid;
justify-content: start;
}
案例6:取值end
.grid-container {
display: grid;
justify-content: end;
}
通过设置align-content属性,可以定义grid项在grid容器中的垂直对齐方式。但是要注意,每一列上,grid项的总高度别超出了grid容器的高度,否则还玩啥呢~
案例1:取值center
.grid-container {
display: grid;
height: 400px;
align-content: center;
}
案例2:取值space-evenly
.grid-container {
display: grid;
height: 400px;
align-content: space-evenly;
}
案例3:取值space-around
.grid-container {
display: grid;
height: 400px;
align-content: space-around;
}
案例4:取值space-between
.grid-container {
display: grid;
height: 400px;
align-content: space-between;
}
案例5:取值start
.grid-container {
display: grid;
height: 400px;
align-content: start;
}
案例6:取值end
.grid-container {
display: grid;
height: 400px;
align-content: end;
}