今天初步學習CSS3的柵格系統,因爲之前學過bootstraps4的柵格系統,所以基本概念是一致的,只是語法上的一些區別,做了一些筆記:
不同的柵格定義方式:
每一格尺寸相同適用重複定義
grid-template-rows:repeat(2,50%); //兩行各佔50%
grid-template-columns:repeat(5,20%); //五列各佔20%
按總容器的比例劃分(fr)
grid-template-rows:1fr 2fr 3fr; 或 repeat(3,1fr);
grid-template-columns:1fr 2fr 2fr;
規定每一柵格的行間距、列間距
grid-row-gap:10px;
grid-colum-gap:10px; 他們等同於:grid-gap:10px 10px;
接下來我在小米移動端官網發現了一塊小型區域很適合柵格系統來完成。
可以看到這是一個左側佔兩行,右側獨佔兩行的佈局。
CSS3:
<style>
.contained{
width:400px;
height:400px;
border: 1px solid #ccc;
display: grid;
grid-template-rows: repeat(2,50%);
grid-template-columns: repeat(2,50%); //定義兩行兩列的柵格容器
grid-row-gap: 10px;
grid-column-gap: 10px; //柵格之間的間距
}
.contained div:nth-child(1){
grid-row-start: 1;
grid-row-end:3; //左側的柵格跨越兩行,從第一根行線連接到第三行線
grid-column-start: 1;
grid-column-end: 2; //獨佔一列
background-color:red;
}
.contained div:nth-child(2){
background-color:blue;
}
.contained div:nth-child(3){
background-color:green;
}
</style>
html:
<body>
<div class = 'contained'>
<div>左側區域1</div>
<div>右側區域1</div>
<div>右側區域2</div>
</div>
</body>
不得不說,有了柵格系統,做靜態佈局真的是思路清晰,特別省事。