如何实现grid布局
时间: 2023-11-24 17:53:19 浏览: 78
在echarts中图例legend和坐标系grid实现左右布局实例
以下是实现grid布局的步骤和示例代码:
1. 在容器上定义display: grid属性,将其设置为网格布局。
```css
.container {
display: grid;
}
```
2. 使用grid-template-columns和grid-template-rows属性定义网格的列和行。
```css
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
}
```
3. 使用grid-column和grid-row属性定义每个项目所占的列和行。
```css
.item {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
```
完整示例代码:
```html
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
<style>
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
}
.item {
background-color: #fff;
border: 1px solid #000;
padding: 10px;
}
.item:nth-child(odd) {
background-color: #eee;
}
.item:nth-child(1) {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
.item:nth-child(2) {
grid-column: 3 / 4;
grid-row: 1 / 3;
}
.item:nth-child(3) {
grid-column: 2 / 3;
grid-row: 2 / 3;
}
.item:nth-child(4) {
grid-column: 1 / 2;
grid-row: 2 / 3;
}
.item:nth-child(5) {
grid-column: 2 / 3;
grid-row: 1 / 2;
}
.item:nth-child(6) {
grid-column: 1 / 2;
grid-row: 1 / 2;
}
</style>
```
阅读全文