css3 flex布局 justify-content:space-between 最后一行左对齐

在使用justify-content:space-between布局时,针对最后一行元素使用 justify-self: start;没有效果,查了下css3 flexbox 还未支持。css

那么如何实现最后一行左对齐呢?

现有的几个方案css3

  • 使用标签元素补全缺的item
  • 使用grid
  • 使用伪类

伪类的状况,若是最后一个元素是满的,会有占位,grid会有兼容问题,又不想新增标签。ide

每一行固定列数的状况实现左对齐方案

因为每一列的数目都是固定的,所以,咱们能够计算出最后一个元素的margin-right值保证彻底左对齐。布局

假设每一行只有3列元素,那么当最后一个元素是第二列(即li:last-child:nth-child(3n + 2))的状况,才须要进行 margin-right处理,距离是一个元素的宽度+空隙宽度。flex

假设元素宽度是$width,上述状况所须要的距离:(100% - 3 * $width) / 2 + $width => (100% - $width) / 2flexbox

.list1  li:last-child:nth-child(3n + 2) {
  margin-right: calc((100% - $width) / 2);
}

image.png

同理,一行4列的状况,须要处理两种状况,最后一个元素在第二列 和 最后一个元素在第三列的状况。spa

.list2  li:last-child:nth-child(4n + 2) {
  margin-right: calc((100% - $width) / 3 * 2);
}
.list2  li:last-child:nth-child(4n + 3) {
  margin-right: calc((100% - $width) / 3 * 1);
}

Kapture 2019-12-25 at 16.33.11.gif

点击这里查看demo 展现代码code

每一行不固定列数的状况实现左对齐方案

这个我以为最好的方案仍是使用grid了,网上一堆,就不作讨论啦。blog

相关文章
相关标签/搜索