售后 :021-51299298 售前 :182-1772-1733 联系我们

flex布局设置space-between,最后一行有缺省时如何左对齐

上海知九信息 flex盒模型 元素对齐 网页布局 CSS web前端 2020-07-04

使用flex弹性布局,两端对齐是设置justify-content:space-between。但是当一行当中的元素有缺省时,不能自动靠左排列,视觉上不够美观,如下图所示:

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伪元素,以上面示例代码为例,样式中增加:

.flex:after {
    content:"";
    width:30%;
}

最终效果

space-between最后一行缺省左对齐