CSS系列-对齐

133 阅读1分钟

问:如何可以让一个元素垂直居中对齐?

1、flex弹性布局

```
display:flex;
justify-content: center;
align-items: center;
```
注:justify-content可选项包括:flex-start(布局方向的开始)、flex-end(布局方向的结束)、
center(居中)、space-between(两端对齐,项目之间的间隔都相等)、
space-around(每个项目两侧都相等,两端留的空间是项目之间间隔的一半)

2、grid布局

display: grid;
justify-items: center;
align-items: center;
注:通过grid布局,可以有多种实现方式,可以通过设定固定行列,然后通过grid-row-start、grid-column-start来实现

3、固定宽高

width: 300px;
height: 300px;
line-height: 300px;
text-align: center;

4、绝对定位

display:absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);

5、通过margin设置水平居中配合其他的方式做垂直居中

margin: 0 auto;
...