![](https://img.haomeiwen.com/i15312191/60837754b15b426c.png)
现象:
这是一段很简单的flex弹性布局代码:
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 的时候,结果是这样的:
![](https://img.haomeiwen.com/i15312191/6958017de3d562a5.png)
现在,我们需要将所有红色格子整体居中,很简单:
将 justify-content: start 改成:justify-content: center 就行了,结果如下:
![](https://img.haomeiwen.com/i15312191/a618c42e4c444355.png)
嗯,OK ! 是我们想要的效果!
接下来,将可视宽度收窄(比如在手机上显示),变成了这样:
![](https://img.haomeiwen.com/i15312191/ffae5ded5fa01849.png)
纳尼?怎么变成这个鬼样子了?flex 布局下,warp之后自动换行,换行后的内容又被居中了。这不太符合一般的排版规则,看起来怪怪的不是吗?
解决
搜了很多资料,发现这个问题还不怎么好解决,算是 flex 弹性布局的一个缺陷吧,如果要最后一行与第一行对齐,我们只能将 justify-content 设为 start, 但这样一来就失去了居中的效果。屏幕右边会空出一截来。但是,为了居中,我们将 justify-content 设为 center后,最后一行又非常别扭地立在屏幕正中,也很突兀。
解决方案是换用grid布局:
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;
}
换用以上代码后,显示如下:
![](https://img.haomeiwen.com/i15312191/5ba8363f0d435946.png)
网友评论