CSS flex布局最后一行左对齐

行数固定

  • 方法一 用margin 模拟缝隙
.container {
    display: flex;
    flex-wrap: wrap;
}
.list {
    width: 24%; height: 100px;
    background-color: skyblue;
    margin-top: 15px;
}
.list:not(:nth-child(4n)) {
    margin-right: calc(4% / 3);
}
  • 方法二 根据最后一行个数确定margin

假设每行4个元素,结果最后一行只有3个元素,则最后一个元素的margin-right大小是“列表宽度+间隙大小”的话,那最后3个元素也是可以完美左对齐的

借助树结构伪类数量匹配技术,可以知道最后一行有几个元素

.list:last-child:nth-child(4n - 1)说明最后一行,要么3个元素,要么7个元素……
.list:last-child:nth-child(4n - 2)说明最后一行,要么2个元素,要么6个元素……

.container {
    display: flex;
    /* 两端对齐 */
    justify-content: space-between;
    flex-wrap: wrap;
}
.list {
    width: 24%; height: 100px;
    background-color: skyblue;
    margin-top: 15px;
}
/* 如果最后一行是3个元素 */
.list:last-child:nth-child(4n - 1) {
    margin-right: calc(24% + 4% / 3);
}
/* 如果最后一行是2个元素 */
.list:last-child:nth-child(4n - 2) {
    margin-right: calc(48% + 8% / 3);
}
  • 如果子元素的宽度不固定 上边的方法就不能用了
    1. 最后一项margin-right:auto;
.container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}
.list {
    background-color: skyblue;
    margin: 10px;
}
/* 最后一项margin-right:auto */
.list:last-child {
    margin-right: auto;
}
  1. 父级创建伪元素并设置flex:auto或flex:1
.container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}
.list {
    background-color: skyblue;
    margin: 10px;
}
/* 使用伪元素辅助左对齐 */
.container::after {
    content: '';
    flex: auto;    /* 或者flex: 1 */
}
  • 如果每一行列数不固定
//HTML代码:
//比div少一个即可!
//CSS代码: .container { display: flex; justify-content: space-between; flex-wrap: wrap; margin-right: -10px; } .list { width: 100px; height:100px; background-color: skyblue; margin: 15px 10px 0 0; } .container > i { width: 100px; margin-right: 10px; }

原文链接地址:https://blog.csdn.net/lbchenxy/article/details/100654731?utm_medium=distribute.pc_relevant.none-task-blog-baidulandingword-10

你可能感兴趣的:(CSS flex布局最后一行左对齐)