容器属性
使用网格布局
/*
使用网格布局,且容器为块级元素
*/
.container {
display: grid;
}
/*
使用网格布局,且容器为行内块元素
*/
.container {
display: inline-grid;
}
- 设为网格布局以后,容器子元素(项目)的float、display: inline-block、display: table-cell、vertical-align和column-*等设置都将失效。
设置行列
固定列数
# 6列,分别宽度为100px 20px 80px 100px 20px 80px
grid-template-columns: repeat(2, 100px 20px 80px);
# 3列 平分
grid-template-columns: repeat(3, 1fr);
# 3列 第一列50px 第二三列平分剩余空间 第二列占1份 第三列占2份
grid-template-columns: 50px 1fr 2fr;
- 未设置行时,自动生成
列数不定
# 每列100px,一行宽度不够,自动换下一行
grid-template-columns: repeat(auto-fill, 100px);
- auto-fill与auto-fit基本一致
- auto-fill会用空格子填满剩余宽度,auto-fit则会尽量扩大单元格的宽度
多余网格设置宽高
/* 多余行 设置宽 */
grid-auto-columns: 100px;
/* 多余行 设置高 */
grid-auto-rows: 100px;
网格线命名
grid-template-columns: [c1] 100px [c2] 100px [c3] auto [c4];
grid-template-rows: [r1] 100px [r2] 100px [r3] auto [r4];
行列间距
row-gap: 10px;
column-gap: 20px;
/* 简写 */
gap: 10px 20px;
划分区域
/* 9个区域 a-i */
grid-template-areas: 'a b c'
'd e f'
'g h i';
/* 3个区域 a b c */
grid-template-areas: 'a a a'
'b b b'
'c c c';
/*
6个区域
点. 表示没有用到该单元格,或者该单元格不属于任何区域
*/
grid-template-areas: 'a . c'
'd . f'
'g . i';
排列方向
/* 默认值,先行后列 */
grid-auto-flow: row;
/* 先列后行 */
grid-auto-flow: row;
(所有)单元格内容对齐方式
justify-items: start | end | center | stretch;
align-items: start | end | center | stretch;
/* 简写 */
place-items: <align-items> <justify-items>;
容器对齐方式
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
align-content: start | end | center | stretch | space-around | space-between | space-evenly;
/* 简写 */
place-content: <align-content> <justify-content>
项目属性
项目放置的区域
/* 该单元格放置到区域e */
grid-area: e;
/* 坐标(1,2)到(3,4)的区域 */
grid-area: 1/2/3/4;
(单个)单元格内容对齐方式
justify-self: start | end | center | stretch;
align-self: start | end | center | stretch;
/* 简写 */
place-self: <align-self> <justify-self>;