Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

现象:

这是一段很简单的flex弹性布局代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
HTML:
<div>
<div class="flex-test">
<div class="box-test">1</div>
<div class="box-test">2</div>
<div class="box-test">3</div>
<div class="box-test">4</div>
<div class="box-test">5</div>
<div class="box-test">6</div>
<div class="box-test">7</div>
<div class="box-test">8</div>
</div>
</div>

CSS这边是这样:
<style>
.flex-test {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: start;
background: blue;
}

.box-test {
height: 100px;
width: 100px;
background: red;
margin: 10px;
}
</style>

justify-content: start 的时候,结果是这样的:

现在,我们需要将所有红色格子整体居中,很简单:
将 justify-content: start 改成:justify-content: center 就行了,结果如下:

嗯,OK ! 是我们想要的效果!
接下来,将可视宽度收窄(比如在手机上显示),变成了这样:

纳尼?怎么变成这个鬼样子了?flex 布局下,warp之后自动换行,换行后的内容又被居中了。这不太符合一般的排版规则,看起来怪怪的不是吗?

解决

搜了很多资料,发现这个问题还不怎么好解决,算是 flex 弹性布局的一个缺陷吧,如果要最后一行与第一行对齐,我们只能将 justify-content 设为 start, 但这样一来就失去了居中的效果。屏幕右边会空出一截来。但是,为了居中,我们将 justify-content 设为 center后,最后一行又非常别扭地立在屏幕正中,也很突兀。

解决方案是换用grid布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
HTML:
<div class="grid-test">
<div class="box-test">1</div>
<div class="box-test">2</div>
<div class="box-test">3</div>
<div class="box-test">4</div>
<div class="box-test">5</div>
<div class="box-test">6</div>
<div class="box-test">7</div>
<div class="box-test">8</div>
</div>
</div>

CSS:
.grid-test {
display: grid;
grid-template-columns: repeat(auto-fill, 100px);
grid-gap: 10px;
justify-content: center;
background: blue;
}

.box-test {
height: 100px;
width: 100px;
background: red;
margin: 10px;
}

换用以上代码后,显示如下:

预览地址

评论