实现:每行固定 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;
}
相关推荐
放下华子我只抽RuiKe53 小时前
React 从入门到生产(六):路由与导航
前端·人工智能·深度学习·react.js·前端框架·html·claude code
文滨3 小时前
10分钟搞定!Mac 配置 GitHub SSH 完全指南(小白也能看懂)
前端·macos·ssh·github
时寒的笔记3 小时前
11期_js逆向核心案例解析(sichuan&某理财网)
开发语言·javascript·ecmascript
2601_958492553 小时前
7 WordPress Tools I Trust for Building a High-Traffic Magazine Site
前端·word
IT_陈寒3 小时前
Java的finally块竟然不是你想的那个finally!
前端·人工智能·后端
2501_940041743 小时前
挖掘前端交互潜力的五款创意游戏原型
前端·游戏
C+-C资深大佬3 小时前
变量作用域(通俗 + 清晰讲解,适合编程入门)
前端·javascript·vue.js
weelinking3 小时前
【claude】15_Claude使用经验与最佳实践
前端·人工智能·python·sql·数据挖掘·前端框架·github