Reference CSS reference

CSS flex 参考

Flexbox 是一维布局模型,适合把元素沿主轴排列,例如导航、按钮组、表单行、卡片内部内容。

语法

css
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

常用属性

属性 作用位置 说明
display: flex 容器 启用 Flexbox
flex-direction 容器 主轴方向
justify-content 容器 主轴对齐
align-items 容器 交叉轴对齐
gap 容器 项目间距
flex-wrap 容器 是否换行
flex 项目 伸缩比例和基础尺寸

可运行演示

在线代码演示
源码
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>flex 工具栏演示</title>
    <style>
      body { margin: 0; padding: 24px; font-family: system-ui, sans-serif; background: #f8fafc; color: #0f172a; }
      .toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; max-width: 760px; margin: 0 auto; padding: 16px; border: 1px solid #dbeafe; border-radius: 12px; background: #fff; }
      .actions { display: flex; gap: 8px; flex-wrap: wrap; }
      button { padding: 8px 12px; border: 0; border-radius: 8px; background: #2563eb; color: #fff; cursor: pointer; }
      .secondary { background: #dbeafe; color: #1e3a8a; }
    </style>
  </head>
  <body>
    <div class="toolbar">
      <strong>项目列表</strong>
      <div class="actions">
        <button class="secondary">筛选</button>
        <button>新建</button>
      </div>
    </div>
  </body>
</html>

常见错误

  • 把二维布局强行写成多层 flex,复杂卡片列表更适合 Grid。
  • 忘记 min-width: 0,导致 flex 子项中的长文本无法收缩。
  • justify-content 和 align-items 方向混淆,先确认主轴方向。

相关内容