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;
}