实现:每行固定 5 个、自动换行、最后一行左对齐、数量不固定

1、Flex 布局实现:每行 5 个,最后一行左对齐(删除 justify-content: space-around,使用 width: calc(20% - 8px) + gap 实现每行 5 个,最后一行自然左对齐)

javascript 复制代码
<template>
    <div class="flex-container">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
    <div class="flex-item">4</div>
    <div class="flex-item">5</div>
    <div class="flex-item">6</div>
    <div class="flex-item">7</div>
    <div class="flex-item">8</div>
    <div class="flex-item">9</div>
    <div class="flex-item">10</div>
    <div class="flex-item">11</div>
    <div class="flex-item">12</div>
    <div class="flex-item">13</div>
  </div>
</template>

<script>

</script>

<style lang="less" scoped>
   /* 父容器:核心 flex 配置 */
    .flex-container {
      display: flex;
      flex-wrap: wrap; /* 自动换行 */
      gap: 10px; /* 盒子之间的间距(可修改) */
    }

    /* 子盒子:固定每行5个 */
    .flex-item {
      /* 核心公式:(100% - 4个间距) / 5 */
      width: calc(20% - 8px); 
      height: 80px;
      background: #409eff;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
    }
</style>

2、如果项目里必须保留 justify-content: space-around,可以用伪元素填充:

html 复制代码
.flex-container::after {
  content: "";
  flex: auto;
  max-width: calc(20% - 10px);
}

3、Grid 网格布局(最推荐,最简单)

Grid 天生就是做多列等宽网格 ,不用算百分比、不用处理间距 ,直接定义 5列,自动换行,最后一行天然左对齐,完全没有 flex space-around 最后一行散开的问题。

html 复制代码
.container {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 固定5列,均分宽度 */
  gap: 10px; /* 间距 */
}
.item {
  height: 80px;
  background: #409eff;
}

4、传统 Float 浮动布局(兼容老项目)

最老的方案,IE 也能用,每行 5 个,自动换行,最后一行天然左对齐。缺点:需要清除浮动。

复制代码
.container::after { /* 清除浮动 */
  content: "";
  display: block;
  clear: both;
}
.item {
  float: left;
  width: calc(20% - 8px);
  margin: 0 4px 10px;
  height: 80px;
  background: #409eff;
}
相关推荐
非优秀程序员1 小时前
第10章 千团出世|《互联网产品恩仇录》
前端
非优秀程序员1 小时前
第11章 小高在对面|《互联网产品恩仇录》
前端
非优秀程序员1 小时前
第14章 只剩美团|《互联网产品恩仇录》
前端
非优秀程序员2 小时前
第09章 老乡何必为难老乡|《互联网产品恩仇录》
前端
非优秀程序员2 小时前
第07章 孙德良的阳谋|《互联网产品恩仇录》
javascript·后端
非优秀程序员2 小时前
第03章 三大门户,烽烟起于瀛海威|《互联网产品恩仇录》
前端
程序员大阳5 小时前
HTML+CSS+JS对话式实战(5)-活动管理页之查看报名名单的实现
javascript·css·html·查看报名名单
曦樂~6 小时前
【Web Development】02 CSS
前端·css
风骏时光牛马6 小时前
后端服务接口开发与数据逻辑处理
前端
东鹏特饮6 小时前
经典打砖块(Breakout)游戏
前端·css·css3