flex布局设置justify-content为space-between,最后一个元素无法右对齐

给flex盒子设置justify-content:space-between,双行排列时出现最后一个元素无法右侧对齐的情况,如下图所示。

space-between最后一个元素无法右对齐
可以看到item4和item2在右侧没有对齐,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{margin: 0;padding: 0;}
		.box {width: 400px;background: #eee;float: left;padding: 5%;}
		.flex {display: flex;flex-wrap: wrap;justify-content: space-between;}
		.clearfix:after {
			content: "";
			display: block;
			height: 0;
			clear: both;
		}
		.item {width: 45%;height: 100px;margin-bottom:10%;background:#fff;list-style:none;text-align: center;line-height: 100px;font-size:20px;color:#333;}
		.item:nth-child(n+3) {margin-bottom: 0;}
	</style>
</head>
<body>
	<div class="box">
		<ul class="flex clearfix">
			<li class="item">1</li>
			<li class="item">2</li>
			<li class="item">3</li>
			<li class="item">4</li>
		</ul>
	</div>
</body>
</html>

有两种解决方法:

  1. 将.item的margin-left或者margin-right或两者同时设置为auto,这个方法部分情况下左右会出现margin值,不能真正两端撑到flex盒子边缘,如下图1;
  2. 另一种方法是去掉.clearfix用于清除浮动的:after伪元素,即可实现最终想要的效果,如下图2.

flex子元素左右两端出现margin
space-between两端对齐

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值