肉渣教程

Grid 容器

上一节 下一节

Grid容器(container)

如果想要把某个HTML元素当作Grid容器,将其display属性设置成gridinline-grid即可。Grid容器的直接子元素则自动成为Grid项,Grid项会被放在Grid容器的行列中。

grid-template-columns属性

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-template-rows属性定义grid容器内每行高度如何。

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto;
  grid-template-rows: 120px 240px;
}

运行一下

justify-content属性

通过设置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属性

通过设置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;
}

运行一下


Grid 容器

上一节 下一节