flex子元素宽度不固定最后一行左对齐实例页面

回到相关文章 »

效果:

方法1:最后一项margin-right: auto

方法2:::after伪元素flex:auto或flex:1

代码:

CSS代码:
.container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 500px;
    max-width: 100%;
}
.list {
    background-color: skyblue;
    margin: 10px;
}
/* 方法1 */
.container:nth-of-type(1) > :last-child {
    margin-right: auto;
}
/* 方法2 */
.container:nth-of-type(2)::after {
    content: '';
    flex: auto;    /* 或者flex: 1 */
}
HTML代码:
<!-- 两个方法HTML都是下面这个 -->
<div class="container">
    <canvas class="list" width="40" height="50"></canvas>
    <canvas class="list" width="60" height="30"></canvas>
    <canvas class="list" width="50" height="60"></canvas>
    <canvas class="list" width="70" height="30"></canvas>
    <canvas class="list" width="80" height="50"></canvas>
    <canvas class="list" width="70" height="70"></canvas>
    <canvas class="list" width="60" height="50"></canvas>
    <canvas class="list" width="40" height="50"></canvas>
    <canvas class="list" width="50" height="60"></canvas>
    <canvas class="list" width="70" height="30"></canvas>
    <canvas class="list" width="80" height="50"></canvas>
</div>