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

问题

flex 布局最后一行没有进行左对齐显示:
在这里插入图片描述

<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,从而实现左对齐的效果

<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 即可

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

鼠标移入移出效果,可以看到最后一行的元素进行了左对齐:
在这里插入图片描述

相关推荐

  1. CSS-Flex布局

    2024-01-26 23:28:03       28 阅读
  2. css flex布局详解

    2024-01-26 23:28:03       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-26 23:28:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-26 23:28:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-26 23:28:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-26 23:28:03       20 阅读

热门阅读

  1. Python中写入csv格式文件出现乱码的解决方法

    2024-01-26 23:28:03       32 阅读
  2. Git 对文件名大小写不敏感的问题解决方案

    2024-01-26 23:28:03       41 阅读
  3. 常见的循环结构

    2024-01-26 23:28:03       33 阅读
  4. 温湿度传感器的工作原理

    2024-01-26 23:28:03       29 阅读
  5. ChatGPT AI革命-阅读心得

    2024-01-26 23:28:03       48 阅读
  6. 数字图像处理:图像内插

    2024-01-26 23:28:03       36 阅读
  7. python+matlab text(按图的相对位置显示)

    2024-01-26 23:28:03       36 阅读
  8. Element-plus修改样式

    2024-01-26 23:28:03       29 阅读
  9. leedcode串联所有单词的子串

    2024-01-26 23:28:03       39 阅读
  10. WebSocket详解及使用教程:打造高效的实时通信

    2024-01-26 23:28:03       30 阅读