构造一个5*5的网格,如下图所示,同一颜色表示同个区域,黑线表示间隔5px
1.普通方式建立网格
<!DOCTYPE html> <html> <body> <style> .d1{ background: skyblue; /* justify-self和align-self都是调整子元素内部内容的(start,end,center) justify-self: center; align-self: end; */ /* grid-row: (从上往下)第一条线 / 最后一条线 grid-column: (从左往右)第一条线 / 最后一条线 */ grid-row: 1/6; grid-column: 1/2; } .d2{ background:green; grid-row: 1/2; grid-column: 2/6; } .d3{ background:red; grid-row:2 / 5; grid-column:2 / 4; } .d4{ background: yellow; grid-row: 2 / 6; grid-column: 4 / 6; } .d5{ background:black; color: white; grid-row: 5 / 6; grid-column: 2 / 4; } .container { font-size: 40px; width: 300px; margin: auto; background: white; /* 表示该父元素下应用网格 */ display: grid; grid-template-rows: 1fr 1fr 1fr 50px auto; grid-template-columns: 50px 50px 50px 50px 50px; /* 行间隔:grid-row-gap: 5px; 列间隔:grid-column-gap: 5px; */ /* 行+列间隔5px */ grid-gap: 5px; /* justfy-items和align-items,所有子元素横纵向对齐(start,end,center) justfy-items: center; align-items: end; */ } </style> <div class="container"> <div class="d1">1</div> <div class="d2">2</div> <div class="d3">3</div> <div class="d4">4</div> <div class="d5">5</div> </div> </body> </html>
2.使用区域模板划分网格
<!DOCTYPE html> <html> <body> <style> .d1{ background: skyblue; grid-area: blue; } .d2{ background:green; grid-area: green; } .d3{ background:red; grid-area: red; } .d4{ background: yellow; grid-area: yellow; } .d5{ background:black; color: white; grid-area: black; } .container { font-size: 40px; width: 300px; margin: auto; background: white; /* 表示该父元素下应用网格 */ display: grid; /* 设置网格模板 **-rows:行数,**-columns:列数 */ /* 五个自适应行 repeat代表重复 */ grid-template-rows: repeat(5,1fr); /* 填充20-50px的方块到列 */ grid-template-columns: repeat(auto-fit, minmax(20px, 50px)); grid-gap: 5px; grid-template-areas: "blue green green green green" "blue red red yellow yellow" "blue red red yellow yellow" "blue red red yellow yellow" "blue black black yellow yellow"; } </style> <div class="container"> <div class="d1">1</div> <div class="d2">2</div> <div class="d3">3</div> <div class="d4">4</div> <div class="d5">5</div> </div> </body> </html>