Flex布局实现充值价格界面

前言

在一次项目中,当时写一个类似QQ的充值界面。看到UI图时,就想到了用Flex Box进行布局,然后就尴尬了。

1
.container {
2
     display: flex;
3
     justify-content: space-between;
4
     flex-wrap: wrap;
5
}
6
7
.list {
8
       width: 24%;
9
       height: 100px;
10
       background-color: skyblue;
11
       margin-top: 15px;
12
}

由于justify-content: space-between;属性,当数量为7个时,第一行是符合要求的,但第二行剩下3个,它们之间
的距离就很大。

后面在网上寻找了一下,大概两种方案。

如果每一行列数是固定的,则下面两种方法可以实现最后一行左对齐。

模拟space-between和间隙

1
 .container {
2
       display: flex;
3
       flex-wrap: wrap;
4
}
5
6
.list {
7
       width: 24%;
8
       height: 100px;
9
       background-color: red;
10
       margin-top: 15px;
11
}
12
13
.list:not(:nth-child(4n)) {
14
       margin-right: calc(4% / 3);
15
}

根据个数最后一个元素动态margin

1
.container {
2
    display: flex; /* 两端对齐 */
3
    justify-content: space-between;
4
    flex-wrap: wrap;
5
}
6
7
.list {
8
    width: 24%;
9
    height: 100px;
10
    background-color: skyblue;
11
    margin-top: 15px;
12
}
13
14
/* 如果最后一行是3个元素 */
15
.list:last-child:nth-child(4n - 1) {
16
    margin-right: calc(24% + 4% / 3);
17
}
18
19
/* 如果最后一行是2个元素 */
20
.list:last-child:nth-child(4n - 2) {
21
    margin-right: calc(48% + 8% / 3);
22
}

如果列数不固定HTML又不能调整

1
.container {
2
    display: grid;
3
    justify-content: space-between;
4
    grid-template-columns: repeat(auto-fill, 100px);
5
    grid-gap: 10px;
6
}
7
8
.list {
9
    width: 100px;
10
    height: 100px;
11
    background-color: skyblue;
12
    margin-top: 5px;
13
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!