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>

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

相关推荐
mCell2 小时前
使用 useSearchParams 同步 URL 和查询参数
前端·javascript·react.js
mCell4 小时前
前端路由详解:Hash vs History
前端·javascript·vue-router
海上彼尚4 小时前
无需绑卡的海外地图
前端·javascript·vue.js·node.js
1024肥宅4 小时前
手写 call、apply、bind 的实现
前端·javascript·ecmascript 6
科杰智能制造5 小时前
纯前端html、js实现人脸检测和表情检测,可直接在浏览器使用
前端·javascript·html
每天吃饭的羊5 小时前
组件库的有些点击事件是name-click这是如何分装de
前端·javascript·vue.js
x***01065 小时前
SpringSecurity+jwt实现权限认证功能
android·前端·后端
1024肥宅5 小时前
防抖(Debounce)
前端·javascript·ecmascript 6
1024肥宅5 小时前
节流(Throttle)
前端·javascript·ecmascript 6
大怪v6 小时前
【Virtual World 02】两点一线!!!
javascript·css·html