需要在父级元素使用一个伪类,设置flex:1;使伪类自动填充剩余的空间;
这种方式会使最后一行的边距失效
:after {
content: "";
flex: 1;
}
使用margin-right计算;这种方式适合每一行固定列数的情况;
假设每一行只有3列元素,那么当最后一个元素是第二列(即.item:last-child:nth-child(3n + 2)
)的情况,才需要进行 margin-right
处理,距离是一个元素的宽度+空隙宽度。
假设元素宽度是$width
,上述情况所需要的距离:(100% - 3 * $width) / 2 + $width
=> (100% - $width) / 2;
使用 calc() 函数来计算时,通过 #{} 语法将 SCSS 变量转换为 CSS 变量
.item:last-child:nth-child(3n + 2) {
margin-right: calc((100% - #{$width}) / 2);
}
同理,一行4列的情况,需要处理两种情况,最后一个元素在第二列 和 最后一个元素在第三列的情况。
.item:last-child:nth-child(4n + 2) {
margin-right: calc((100% - #{$width}) / 3 * 2);
}
.item:last-child:nth-child(4n + 3) {
margin-right: calc((100% - #{$width}) / 3 * 1);
}
使用grid,适合一行列数不固定的情况
.list {
display: grid;
grid-template-columns: repeat(auto-fill, /*item的宽度*/ 100px);
grid-gap: 10px;
}
.list .item {
width: /*item的宽度*/ 100px;
}
参考文章:css3 flex布局 justify-content:space-between 最后一行左对齐_css3_CSS_网页制作_脚本之家