css 中 flex 布局最后一行实现左对齐

问题

flex 布局最后一行没有进行左对齐显示:

html 复制代码
<div class='parent'>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
	<div class='child'></div>
</div>

<style>
	.parent{
		width: 300px;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
		
	.child{
		width:32%;	
		height: 95px;
		background: #fd775a;
		margin-top: 10px;
	}
</style>

解决方法

1、行的 列数 及 子元素宽度 都固定

给最后一个元素加上右侧的外边距 margin-right,从而实现左对齐的效果

html 复制代码
<style>
	.parent{
		width: 300px;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
		
	.child{
		width:32%;	
		height: 95px;
		background: #fd775a;
		margin-top: 10px;
	}

	.child:last-child { //定位最后一个元素设置右侧外边距
		margin-right: calc(32% + 4% / 3); //具体数值根据实际情况填入
	}
</style>

效果:

2、子元素宽度不固定

与上一个方法同理,只需要把最后一个元素的 margin-right 设置为 auto 即可

html 复制代码
<style>
	.parent{
		width: 600px;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	.parent:hover{
		width: 540px;
	}
		
	.child{
		height: 95px;
		background: #fd775a;
		margin-top: 10px;
		margin-left: 10px;
	}
	
	.child:last-child {
		margin-right: auto;
	}
</style>

<div class='parent'>
	<div class='child' style="width:50px"></div>
	<div class='child' style="width:130px"></div>
	<div class='child' style="width:100px"></div>
	<div class='child' style="width:150px"></div>
	<div class='child' style="width:80px"></div>
	<div class='child' style="width:110px"></div>
	<div class='child' style="width:90px"></div>
	<div class='child' style="width:60px"></div>
	<div class='child' style="width:200px"></div>
	<div class='child' style="width:60px"></div>
</div>

鼠标移入移出效果,可以看到最后一行的元素进行了左对齐:

相关推荐
崔庆才丨静觅15 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606115 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了15 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅15 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅16 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅16 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment16 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅17 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊17 小时前
jwt介绍
前端
爱敲代码的小鱼17 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax