一些关于 grid 的笔记
声明栅格系统的容器
css.box { /* 如果想作为块级元素 */ display: grid; /* 如果想作为行内块元素 */ display: inline-grid; /* 设置每列 */ grid-template-rows: /* 第一种写法: 10px 10px 10px 10px //设置每个块占多大 */ /* 第二种写法: 25% 25% 25% 25% */ /* 第三种写法: repeat(4, 25%) */ /* 第三种写法延伸:repeat(2, 100px 50px) //将100px和50px重复两遍 */ /* 第三种写法延伸:repeat(auto-fill, 100px) //以100px自动填充 */ /* 第四种写法:repeat(3,1fr) //填充3块,平均分配 */ /* 设置每行 */ grid-template-columns: 写法同上 } .content { background: blueviolet; background-clip: content-box; box-sizing: border-box; border: solid 1px blueviolet; padding: 10px; }
控制栅格尺寸范围
css.box { ... grid-template-rows: repeat(2,minmax(50px,100px)) }
用栅格间距控制留白
css.box { ... row-gap: 10px; column-gap: 10px; /* 简写 */ gap: 20px 10px; }
根据栅格线编号放置元素
cssdiv:first-child { grid-row-start: 1; grid-column-start: 1; grid-column-end: 4; grid-row-end: 4; }
栅格固定命名放置元素
css.box { grid-template-rows: [r1-start] 100px [r1-end r2-start] 100px [r2-end r3-start] 100px [r3-end]; } .content { grid-row-start: r1-start; /* 以此类推 */ }
更简洁的 repeat 写法:
css.box { grid-template-rows: repeat(3, [r-start] 1fr [r-end]); } .content { grid-row-start: r-start 1; /* 第一行的开始 */ grid-column-start: c-start 2; /* 以此类推 */ }
偏移量控制元素定位
cssdiv:first-child { grid-column-end: span 3; /* 相对start偏移3个格子 */ }
偏移量简写
cssdiv:first-child { grid-row: 3/4; /* 相当于start是3,end是4 */ grid-column: 1 / span 3; }
用栅格区域
cssdiv:first-child { grid-area: 2/2/3/3; /* 上左下右 */ }
栅格区域命名
css.box { width: 100vw; height: 100vh; display: grid; grid-template-rows: 60px 1fr 60px; /* 三行 */ grid-template-columns: 60px 1fr; /* 两列 */ grid-template-areas: 'header header' /* 第一行两个区域名字 */ 'nav main' /* 以此类推 */ 'footer footer'; } .content { grid-area: header; /* 用命名的栅格区域 */ }
使用区域占位符,简化栅格区域命名
css.box { width: 100vw; height: 100vh; display: grid; grid-template-rows: 60px 1fr 60px; /* 三行 */ grid-template-columns: 60px 1fr; /* 两列 */ grid-template-areas: '. .' /*用两个点占位 */ '. .' 'footer footer'; /*在想要合并的区域命名 */ } .content { grid-area: header; /*用命名的栅格区域 */ }
栅格流动处理机制
栅格排布顺序
css.box { .. grid-auto-flow: column; /* 一列一列地排列元素。默认为row */ }
让后面的元素填补前面元素因为定位留出的空白
css.box { grid-auto-flow: dense; /* 不填,默认是不会补全 */ }
栅格对齐布局
栅格整体对齐
分开
用 justify-content 和 align-content
组合
place-content:center space-evently 第一个是 align,第二个是 justify
栅格内部所有元素的对齐
分开
justify-items 和 align-items
组合
place-items
栅格内部单个元素对齐
在要控制的单个元素的 css 样式里设置
分开
justify-self 和 align-self
组合
place-self
Article Index