flex布局常用用法

1.flex布局控制子元素的边距

sql 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Flex 三栏布局</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    .flex-container {
      display: flex;
      width: 100%;
      min-height: 100vh;
      background-color: #f5f5f5;
      align-items: center;
      padding: 0; /* 确保无内边距干扰 */
    }

    .item {
      width: 80px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      color: white;
    }

    .item1 {
      background-color: #4CAF50;
      margin-left: 10px;   /* 距离容器左边 10px */
    }

    .item2 {
      background-color: #2196F3;
      margin-left: 20px;   /* 与 item1 间隔 20px */
    }

    .item3 {
      background-color: #FF9800;
      margin-right: 10px;  /* 距离容器右边 10px */
      margin-left: auto;  /* 关键自适应边距*/
    }
  </style>
</head>
<body>
  <div class="flex-container">
    <div class="item item1">1</div>
    <div class="item item2">2</div>
    <div class="item item3">3</div>
  </div>
</body>
</html>

2.使用gap控制子元素中间边距

sql 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>3列等宽 Flex 布局</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    .container {
      display: flex;
      flex-wrap: wrap;
      gap: 10px; /* 水平和垂直间距均为 10px */
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
    }

    .item {
      /* 关键:3列布局,2个间隙 × 10px = 20px */
      flex: 1 1 calc((100% - 20px) / 3);
      min-width: 0; /* 防止长内容撑破布局 */

      background-color: #42b883;
      color: white;
      padding: 20px;
      text-align: center;
      border-radius: 8px;
      font-family: Arial, sans-serif;
    }
  </style>
</head>
<body>
  <div class="container" id="container">
    <!-- 动态生成 8 个 item -->
  </div>

  <script>
    // 使用原生 JS 动态创建 8 个 item(模拟 Vue 的 v-for)
    const container = document.getElementById('container');
    for (let i = 1; i <= 8; i++) {
      const item = document.createElement('div');
      item.className = 'item';
      item.textContent = `Item ${i}`;
      container.appendChild(item);
    }
  </script>
</body>
</html>
相关推荐
kyriewen10 小时前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
IT_陈寒11 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
小林攻城狮11 小时前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦11 小时前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
the_answer12 小时前
Webpack vs Vite 深度对比分析
前端·webpack
转转技术团队12 小时前
验证码识别实战:前端不写页面,改训模型了?
前端
MomentYY12 小时前
Temperature:AI 的“脑洞旋钮”
前端·llm·ai编程
远航_12 小时前
OpenSpec 完整详细介绍
前端·后端
召钱熏13 小时前
状态枚举正确≠渲染正确:一个语音按钮的状态机边界修复实录
android·前端
SkyWalking中文站13 小时前
认识 Horizon UI · 1/17:SkyWalking 新一代可观测性控制台
运维·前端·监控