給flex盒子設置justify-content:space-between,雙行排列時出現最后一個元素無法右側對齊的情況躺盛,如下圖所示项戴。
space-between最后一個元素無法右對齊.jpg
可以看到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>
有兩種解決方法:
- 將.item的margin-left或者margin-right或兩者同時設置為auto槽惫,這個方法部分情況下左右會出現margin值周叮,不能真正兩端撐到flex盒子邊緣,如下圖1界斜;
-
另一種方法是去掉.clearfix用于清除浮動的:after偽元素仿耽,即可實現最終想要的效果,如下圖2.
flex子元素左右兩端出現margin.jpg
space-between兩端對齊.jpg