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

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

有两种解决方法:

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


    flex子元素左右两端出现margin.jpg

    space-between两端对齐.jpg

原文链接:http://www.web315.net/doc/49.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。