参考阮一峰老师的博客写的学习笔记。
1. 基本概念
容器与项目、行与列、单元格、网格线
容器属性、项目属性
2. 容器属性
2.1 grid-template-columns 属性, grid-template-rows 属性
基本属性
display: grid //指定容器为网格布局
grid-template-columns: repeat(3, 33.33%); //指定每一列的列宽
grid-template-rows: repeat(3, 33.33%); //指定每一行的行高
auto-fill关键字: 单元格大小固定,希望每一行/列尽可能多的容纳单元格
display: grid
grid-template-columns: repeat(auto-fill, 100px);
fr关键字:fraction,意为片段,用于表示比例关系。会按比例分配剩余空间。 如果两列的宽度分别为1fr和2fr,则表示后者是前者的两倍。 下例表示第一列为100px,第二列和第三列宽度相同。
display: grid;
grid-template-columns: 100px 1fr 1fr;
minmax()关键字:产生长度范围。接受min和max两个参数。
auto关键字: 由浏览器自己决定剩余长度。
网格线的名称:在grid-template-columns中使用方括号可以指定每一根网格线的名字,方便引用。
display: grid;
grid-template-columns: [c1] 100px [c2] 100px [c3] auto [c4];
grid-template-rows: [r1] 100px [r2] 100px [r3] auto [r4];
布局实例 两栏布局:
.wrapper {
display: grid;
grid-template-columns: 30% 70%;
}
2.2 row-gap 属性, column-gap 属性, gap 属性
基本属性
row-gap属性设置行与行的间隔(行间距),column-gap属性设置列与列的间隔(列间距)。
gap是两者的合并简写形式,
grid-gap: <grid-row-gap> <grid-column-gap>;
2.3 grid-template-areas 属性
网格布局允许指定"区域"(area),一个区域由单个或多个单元格组成。 布局实例:
grid-template-areas: "header header header"
"main main sidebar"
"footer footer footer";
2.4 grid-auto-flow 属性
划分网格以后,容器的子元素会按照顺序,自动放置在每一个网格。默认的放置顺序是"先行后列",这个顺序由grid-auto-flow决定,默认值为row。
grid-auto-flow: row dense
2.5 justify-items 属性, align-items 属性, place-items 属性
justify-items属性设置单元格内容的水平位置(左中右),align-items属性设置单元格内容的垂直位置(上中下)。
.container {
justify-items: start | end | center | stretch;
align-items: start | end | center | stretch;
}
- start:对齐单元格的起始边缘。
- end:对齐单元格的结束边缘。
- center:单元格内部居中。
- stretch:拉伸,占满单元格的整个宽度(默认值)。
place-items属性是align-items属性和justify-items属性的合并简写形式。
place-items: <align-items> <justify-items>;
2.6 ### justify-content 属性, align-content 属性, place-content 属性
justify-content属性是整个内容区域在容器里面的水平位置(左中右),align-content属性是整个内容区域的垂直位置(上中下)。
.container {
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
align-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
- space-around - 每个项目两侧的间隔相等。所以,项目之间的间隔比项目与容器边框的间隔大一倍。
- space-between - 项目与项目的间隔相等,项目与容器边框之间没有间隔。
- space-evenly - 项目与项目的间隔相等,项目与容器边框之间也是同样长度的间隔。
place-content属性是align-content属性和justify-content属性的合并简写形式。
place-content: <align-content> <justify-content>
2.7 grid-auto-columns 属性, grid-auto-rows 属性
用来设置浏览器自动创建的多余网格的列宽和行高。
3.项目属性
3.1 grid-column-start 属性, grid-column-end 属性, grid-row-start 属性, grid-row-end 属性
该属性指定项目的四个边框位于哪根网格线,可以指定值,也可以指定网格线的名字。
该属性也可以使用span关键字,表示左右(上下)边框之间跨越多少个网格。
3.2 grid-column属性,grid-row属性
3.1属性的合并简写
3.3 grid-area 属性
用途1:指定项目放在哪个区域 用途2:作为3.1的合并简写
.item {
grid-area: <row-start> / <column-start> / <row-end> / <column-end>;
}
4.4 justify-self 属性, align-self 属性, place-self 属性
设置单元格内容的水平位置,只作用于单个项目
.item {
justify-self: start | end | center | stretch;
align-self: start | end | center | stretch;
}
stretch是默认属性,占满单元格(拉伸)。
place-self属性是align-self属性和justify-self属性的合并简写形式。
place-self: <align-self> <justify-self>;
如果省略第二个值,place-self属性会认为这两个值相等。