返回博客列表
CSSCSS布局GridFlexbox

现代 CSS 布局技术:Grid vs Flexbox

WyperBlog2024-11-1012 分钟

现代 CSS 布局技术

掌握 Grid 和 Flexbox,轻松实现各种复杂布局。

Flexbox 基础

主轴和交叉轴

css
.container {
  display: flex;
  flex-direction: row; /* row | column */
  justify-content: center; /* 主轴对齐 */
  align-items: center; /* 交叉轴对齐 */
}

常见布局

css
/* 水平居中 */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 等分布局 */
.equal {
  display: flex;
}

.equal > * {
  flex: 1;
}

CSS Grid

网格定义

css
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 100px auto;
  gap: 20px;
}

响应式网格

css
.responsive-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

何时使用?

  • Flexbox: 一维布局(行或列)
  • Grid: 二维布局(行和列)

实战案例

圣杯布局

css
.holy-grail {
  display: grid;
  grid-template-areas:
    "header header header"
    "nav main aside"
    "footer footer footer";
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

总结

Grid 和 Flexbox 各有优势,合理选择能大大提升开发效率。

觉得文章不错?点个赞吧

评论 (0)

还没有评论,来发表第一条评论吧!