CSS 中最后一行中元素如何向左对齐

您所在的位置:网站首页 css靠左侧元素对齐 CSS 中最后一行中元素如何向左对齐

CSS 中最后一行中元素如何向左对齐

2024-01-28 05:15| 来源: 网络整理| 查看: 265

自从CSS 3.0出来以后,很多的页面布局都用弹性布来实现,特别是移动端,但是弹性布局也有它的弊端,就是最后一行如果数量不够,不会像我们正常的想法一样居左对齐。效果如下:

代码如下:

.list { display: flex; justify-content: space-between; flex-wrap: wrap; } .item { width: 24%; height: 100px; background-color: blue; margin-bottom: 15px; } 1. 每行列数是固定的

如果每一行的列的数量是固定的,却列的宽度一样,比如每一行均为4个,宽度均为24%,则可以用两种方法来解决这个问题。

1. 弹性布局,但是不用弹性布局的对齐方式,中间的间隙通过计算得来。

.list { display: flex; flex-wrap: wrap } .item { width: 24%; height: 100px; background-color: blue; margin-bottom: 15px; } /* 非第4列的右边距 */ .item:not(:nth-child(4n)) { margin-right: calc(4% / 3); }

2. 弹性布局,两边对齐,最后一列有2个或是3个时,通过动态计算右边距来解决左对齐问题。

.list { display: flex; flex-wrap: wrap; justify-content: space-between; } .item { width: 24%; height: 100px; background-color: blue; margin-bottom: 15px; } /* 如果最后一行是3个元素 */ .item:last-child:nth-child(4n - 1) { margin-right: calc(24% + 4% / 3); } /* 如果最后一行是2个元素 */ .item:last-child:nth-child(4n - 2) { margin-right: calc(48% + 8% / 3); }2. 子元素宽度不固定

如果每一个子元素宽度不固定,那最后一行如何实现左对齐呢,有以下两种方法。

1. 弹性布局,两边对齐,最后一个元素的右边距设置为自动。

.list { display: flex; justify-content: space-between; flex-wrap:wrap; } .item { background-color: blue; margin: 10px; height:100px; } .item:last-child { margin-right: auto; }

2. 弹性布局,两边对齐,给外层容器添加一个伪元素,伪元素设置 flex:auto 或 flex:1。

.list { display: flex; justify-content: space-between; flex-wrap: wrap; } .list::after { content: ''; flex: auto; } .item { background-color: blue; margin: 10px; height: 100px; }3. 每行列数不固定

如果每一行列数不固定,那最后一行如何实现左对齐呢,有以下两种方法。

1. 使用足够的空白标签进行填充占位,具体的占位数量是由最多列数的个数决定的,一行最多几列,就用几个空白标签。占位的元素的 width 和 margin 设置得和子元素一样即可,其他样式都不需要写。由于占位元素高度为0,因此,并不会影响垂直方向上的布局呈现。

这种方法是使用最广的一种方法,如果有代码洁癖,请忽略。

.list { display: flex; justify-content: space-between; flex-wrap: wrap; } .item { width: 100px; height: 100px; background-color: blue; margin-bottom:10px; margin-right:10px; } .list>i { width: 100px; margin-right: 10px; }

2. 使用格子布局,有天然的间隙和对齐排布,因此,实现最后一行左对齐可以认为是天生的效果。

.list { display: grid; justify-content: space-between; grid-template-columns: repeat(auto-fill, 100px); grid-gap: 10px; } .item { width: 100px; height:100px; background-color: blue; }

格子布局需然很爽,但是 repeat() 函数有一定兼容性要求,在IE浏览器上不支持。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3