柵格(grid)
是一種自適應布局,能根據不同終端自動伸縮容器的寬高。flex根據軸線(axis)
布局,看起來像是一維布局;而grid針對網格線(grid line)
布局,看起來更像是二維布局。
跟flex一樣,grid由柵格容器(grid container)
和柵格項目(grid item)
組成。
柵格容器
通過display: grid
可以將元素聲明為塊級柵格容器,通過display: inline-grid
可以將元素聲明為行內柵格容器。
1. grid屬性
grid
是一個復合屬性,包括grid-template-rows
、grid-template-columns
、grid-template-areas
、grid-auto-rows
、grid-auto-columns
、grid-auto-flow
六個屬性的合並。
1. grid-template-rows屬性
grid-template-rows
屬性,定義每一行的高度。
2. grid-template-columns屬性
grid-template-columns
屬性,定義每一列的寬度。
這兩個屬性除了可以用合理的長度單位之外,還有一些專用的屬性值。
repeat(int,<length>):重復某個值,第1個參數為重復次數,第2個值為長度
auto-fill: 自動填充
fr: fraction(片段),表示比例關系
minmax(<length>,<length>): 數字在這兩個范圍內浮動
auto: 自動計算長度
每個長度之前還可以指定網格線的名字,例如
.container {
display: grid;
grid-template-columns: [c1] 100px [c2] 100px [c3] auto [c4];
grid-template-rows: [r1] 100px [r2] 100px [r3] auto [r4];
}
3. grid-template-areas屬性
grid-template-areas
屬性,定義每個單元格所屬的區域;
// 以九宮格為例,按行書寫
grid-template-areas: "a b c" "d e f" "g h i";
4. grid-auto-rows屬性
grid-auto-rows
屬性,表示自動計算項目的高度。
// 在2*3的容器內,指定某個元素在第4行第2列,此時多出來的單元格高度都為30px
grid-auto-rows: 30px
5. grid-auto-columns屬性
grid-auto-columns
,表示自動計算項目的寬度。
// // 在2*3的容器內,指定某個元素在第4行第2列,此時多出來的單元格寬度都為30px
grid-auto-columns: 30px
6. grid-auto-flow屬性
grid-auto-flow
屬性,表示自動排序項目的方式。
grid-auto-flow: row | column | row dense | column dense;
7. justify-content屬性
justify-content
屬性,表示容器內容的水平排列方向;
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
8. align-content屬性
align-content
屬性,表示容器內容的垂直排列方向;
align-content: start | end | center | stretch | space-around | space-between | space-evenly;
9. place-content屬性
place-content
屬性是align-content
和justify-content
兩個屬性的合並
place-content: <align-content> <justify-content>
10. justify-items屬性
justify-items
屬性,表示單元格內容的水平對齊方式;
justify-items: start | end | center | stretch;
11. align-items屬性
align-items
屬性,表示單元格內容的垂直對齊方式;
align-items: start | end | center | stretch;
12. place-items屬性
place-items
屬性是align-items
和justify-items
屬性的合並。
place-items: <align-items> <justify-items>;
柵格項目
- grid-row-start屬性
grid-row-start
屬性,表示單元格內容的起始柵格線序號;
grid-row-start: <number>;
- grid-row-end屬性
grid-row-end
屬性,表示單元格內容的終止柵格線序號;
grid-row-end: <number>;
- grid-column-start屬性
grid-column-start
屬性,表示單元格內容的起始柵格線序號;
grid-column-start: <number>;
- grid-column-end屬性
grid-column-end
屬性,表示單元格內容的終止柵格線序號;
grid-column-end: <number>;
- grid-column屬性
grid-column
屬性是grid-column-start
屬性和grid-column-end
屬性的合並;
grid-column: <grid-column-start> <grid-column-end>;
- grid-row屬性
grid-row
屬性是grid-row-start
屬性和grid-row-end
屬性的合並;
grid-row: <grid-row-start> <grid-row-end>;
- justify-self屬性
justify-self
屬性,指定單元格內容的水平排列方向;
justify-self: start | end | center | stretch;
- align-self屬性
align-self
屬性,指定單元格內容的垂直排列方向;
align-self: start | end | center | stretch;
- place-self屬性
place-self
屬性是justify-self
和align-self
屬性的合並。
place-self: <align-self> <justify-self>;