当前位置:网站首页>解决flex布局warp自动换行下最后一行居中问题
解决flex布局warp自动换行下最后一行居中问题
2022-08-02 03:26:00 【rockage】

1、现象:
- 这是一段很简单的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 的时候,结果是这样的:

- 现在,我们需要将所有红色格子整体居中,很简单:
将 justify-content: start 改成:justify-content: center 就行了,结果如下:
- 嗯,OK ! 是我们想要的效果!
- 接下来,将可视宽度收窄(比如在手机上显示),变成了这样:

- 纳尼?怎么变成这个鬼样子了?flex 布局下,warp之后自动换行,换行后的内容又被居中了。这不太符合一般的排版规则,看起来怪怪的不是吗?
2、解决
- 搜了很多资料,发现这个问题还不怎么好解决,算是 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;
}
- 换用以上代码后,显示如下:

这是我们想要的效果了,<( ̄︶ ̄)[GO!]~~~
后记
- 一直觉得flex弹性布局是HTML排版的终极方案了,没想到也有不周全的地方,看来还是得双修才是正道。
边栏推荐
猜你喜欢

(1) print()函数、转义字符、二进制与字符编码 、变量、数据类型、input()函数、运算符

CTF之xxe

(4) Function, Bug, Class and Object, Encapsulation, Inheritance, Polymorphism, Copy

利用cookie获取admin权限 CTF基础题

File upload vulnerability

Alfa: 1 vulnhub walkthrough

元宇宙是一个炒作的科幻概念,还是互联网发展的下半场?

SQL注入(6)

web渗透必玩的靶场——DVWA靶场 1(centos8.2+phpstudy安装环境)

成本会计的概念、产品成本核算的要求、产品成本核算的对象与成本项目、产品成本的归集和分配(可能考判断)、产品成本计算方法 (三种:产品的品种(品种法),批次(分批法),步骤(分步法))
随机推荐
(8) requests, os, sys, re, _thread
CTF入门之php文件包含
file contains vulnerabilities
成本会计的概念、产品成本核算的要求、产品成本核算的对象与成本项目、产品成本的归集和分配(可能考判断)、产品成本计算方法 (三种:产品的品种(品种法),批次(分批法),步骤(分步法))
Kali install IDEA
(3) string
Turn trendsoft/capital amount of Chinese capital library
【无标题】
WeChat applet development video loading: [Rendering layer network layer error] Failed to load media
2. PHP variables, output, EOF, conditional statements
(6) Design of student information management system
(4) 函数、Bug、类与对象、封装、继承、多态、拷贝
How to calculate the distance between two points on the earth (with formula derivation)
vim edit mode
Mysql创建索引
The learning path of a network security mouse - the basic use of nmap
元宇宙是一个炒作的科幻概念,还是互联网发展的下半场?
The CTF introduction of PHP file contains
VIKINGS: 1 vulnhub walkthrough
CTF之xxe