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>
相关推荐
子兮曰6 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖6 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神6 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛9 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希9 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
尽意啊9 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜9 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive9 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…9 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.9 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts