0%

CSS Grid vs Flexbox

Grid 和 Flexbox 的区别

Grid 是二维布局,Flexbox 是一维布局。

适用场景

Flexbox

  • 一维布局:行或列
  • 内容驱动:项目大小不确定
  • 空间分配

Grid

  • 二维布局:行和列
  • 设计驱动:固定网格
  • 复杂布局

语法对比

Flexbox

1
2
3
4
5
.container {
display: flex;
justify-content: space-between;
align-items: center;
}

Grid

1
2
3
4
5
6
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 100px 100px;
gap: 10px;
}

组合使用

Grid 用于整体布局,Flexbox 用于内部对齐。

1
2
3
4
5
6
<div class="grid-container">
<header class="flex-header">Header</header>
<main>Main</main>
<aside>Aside</aside>
<footer>Footer</footer>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
.grid-container {
display: grid;
grid-template-areas:
"header header"
"main aside"
"footer footer";
}

.flex-header {
display: flex;
justify-content: space-between;
align-items: center;
}

浏览器支持

  • Flexbox:IE10+
  • Grid:IE11+ (有限支持)

总结

选择取决于布局需求。Grid 适合复杂页面,Flexbox 适合组件内部。