Flex 弹性布局完全指南

159 阅读2分钟

Flex 布局是现代 Web 开发中必不可少的布局方案。本文将结合代码示例详解 Flex 布局的核心特性,助你快速掌握这一强大工具。

一、弹性盒子基础

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

<style>
.container {
  display: flex; /* 启用弹性盒子 */
  border: 2px solid #ccc;
  padding: 10px;
}

.item {
  padding: 20px;
  background: #3498db;
  color: white;
  margin: 5px;
}
</style>

二、主轴对齐方式(justify-content)

/* 默认效果 */
.container {
  justify-content: flex-start;
}

de64a4a1f13b024f0ff772de0aa98bf9.png

/* 居中对齐 */
.center {
  justify-content: center;
}

de3d1b4e4ef0fed0ceb449daf3c5a442.png

/* 两端对齐 */
.space-between {
  justify-content: space-between;
}

4378d550f7891f4fb8cb3bdbc9bfd294.png

三、侧轴对齐方式(align-items)

/* 垂直居中 */
.container {
  height: 200px;
  align-items: center;
}

/* 单独设置某个元素 */
.special-item {
  align-self: flex-end;
}

四、更改主轴方向(flex-direction)

/* 垂直排列 */
.vertical {
  flex-direction: column;
}

eb4d95ed955cbe7385b8077256d5ad78.png

/* 反向排列 */
.reverse {
  flex-direction: row-reverse;
}

e01b0720d74febf76e539968ea9d466c.png

五、弹性比例(flex)

<div class="flex-container">
  <div class="item" style="flex: 1">1份</div>
  <div class="item" style="flex: 2">2份</div>
  <div class="item" style="flex: 1">1份</div>
</div>

六、换行与多行对齐(flex-wrap + align-content)

.wrap-container {
  flex-wrap: wrap;
  height: 300px;
  align-content: space-around;
}

.item {
  width: 30%; /* 强制换行 */
}

909fe406ae8e0ddef2634824280a926b.png

七、综合案例:响应式导航栏

<nav class="navbar">
  <div class="logo">LOGO</div>
  <div class="menu">
    <a href="#">首页</a>
    <a href="#">产品</a>
    <a href="#">关于</a>
    <a href="#">联系</a>
  </div>
  <div class="user">用户</div>
</nav>

<style>
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
}

.menu {
  display: flex;
  gap: 20px; /* 项目间距 */
}

@media (max-width: 768px) {
  .navbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .menu {
    flex-direction: column;
    text-align: center;
  }
}
</style>

八、Flex 布局速查表

属性常用值说明
displayflex创建弹性容器
flex-directionrow/column主轴方向
justify-contentspace-between主轴对齐
align-itemscenter侧轴对齐
flex-wrapwrap允许换行
flex1/2/3分配剩余空间

九、最佳实践技巧

  1. 优先使用 gap 属性设置项目间距
  2. 组合使用 flex: 1 实现等分布局
  3. 响应式布局配合媒体查询修改 flex-direction
  4. 使用 min-width 防止内容过度挤压

图片来源:

建议通过 Chrome DevTools 的 Flexbox 调试工具实时观察布局变化,这将极大提升学习效率。