使用flex弹性布局,两端对齐是设置justify-content:space-between。但是当一行当中的元素有缺省时,不能自动靠左排列,视觉上不够美观,如下图所示:
图示示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
.box {width: 400px;background: #1f1f1f;float: left;padding: 2%;}
.flex {display: flex;flex-wrap: wrap;justify-content: space-between;}
.item {width: 30%;height: 80px;margin-bottom:5%;background:#fff;list-style:none;text-align: center;line-height: 80px;font-size:20px;color:#333;}
.item:nth-child(n+4) {margin-bottom: 0;}
</style>
</head>
<body>
<div class="box">
<ul class="flex">
<li class="item">1</li>
<li class="item">2</li>
<li class="item">3</li>
<li class="item">4</li>
<li class="item">5</li>
</ul>
</div>
</body>
</html>
解决方法也很简单,为flex容器设置宽度与子元素相同的:after伪元素(2021-03-23更新:缺几个就等于几个子元素宽度,详见评论),以上面示例代码为例,样式中增加:
.flex:after {
content:"";
width:30%;
}
最终效果
转载自:http://www.web315.net/doc/64.html