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>

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

相关推荐
10年前端老司机2 小时前
10道js经典面试题助你找到好工作
前端·javascript
小小小小宇8 小时前
TS泛型笔记
前端
小小小小宇8 小时前
前端canvas手动实现复杂动画示例
前端
codingandsleeping8 小时前
重读《你不知道的JavaScript》(上)- 作用域和闭包
前端·javascript
小小小小宇8 小时前
前端PerformanceObserver使用
前端
charlee449 小时前
给Markdown渲染网页增加一个目录组件(Vite+Vditor+Handlebars)(下)
css·markdown·响应式设计·flexbox·粘性定位
zhangxingchao9 小时前
Flutter中的页面跳转
前端
烛阴10 小时前
Puppeteer入门指南:掌控浏览器,开启自动化新时代
前端·javascript
全宝11 小时前
🖲️一行代码实现鼠标换肤
前端·css·html
小小小小宇11 小时前
前端模拟一个setTimeout
前端