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>

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

相关推荐
Csvn5 分钟前
框架性能优化
前端
回眸&啤酒鸭2 小时前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013842 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员2 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子2 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒2 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend3 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
海码事务所4 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI4 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场4 小时前
命令行中文变问号 我用环境变量救了场
前端·electron