Skip to main content

CSS 的垂直居中的方法

垂直居中是布局中十分常见的效果之一,为实现良好的兼容性,PC 端实现垂直居中的方法一般是通过绝对定位,table-cell,负边距等方法。有了 css3,针对移动端的垂直居中就更加多样化。

text-align: center 这个属性是针对于行内文本居中的,对于 div 这种块级元素是不可以居中的

方法 1:table-cell

html 结构:

::: demo table-cell 垂直居中

<template>
<div class="box">
<div class="chilbox"></div>
</div>
</template>
<script>
export default {
}
</script>
<style>
.box {
display: table-cell;
vertical-align: middle;
width: 400px;
height: 400px;
border: 1px solid;
}

.chilbox {
background: red;
width: 200px;
height: 200px;
margin: auto;
}
</style>
:::


## 方法 2:display:flex

::: demo display: flex 垂直居中
```html
<template>
<div class="box1">
<div class="chil1"></div>
</div>
</template>
<script>
export default {
}
</script>
<style>
.box1 {
display: flex;
justify-content:center;
align-items: center;
width: 400px;
height: 400px;
color: black;
border: 1px solid;
}

.chil1 {
background: red;
width: 200px;
height: 200px;
}
</style>
:::

## 方法 3:translate

```html
<div class="box2 ">
<div class="box3"></div>
</div>
.box2 { 
position:relative;
border:1px solid;
width: 400px;
height: 400px;
}

.box3 {
position: absolute;
width:200px;
height: 200px;
top:50%;
left:50%;
transform: translate(-50%,-50%);
background: red;
}

这个方法不需要知道自己的宽高都可以,因为 translate(-50%,-50%) 代表着偏移自身的 50%

方法 4:固定高度宽度绝对定位

<div class="father">
<div></div>
</div>
.father {
width: 400px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px; /** 200/2 = 100 */
margin-left: -200px; /** 400/2 = 200 */
background: yellow;
}

也可以用 calc 来优化代码

.father {
width: 400px;
height: 200px;
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 200px);
background: yellow;
}

因为如果不进行偏移的话,本身自己有长宽,那么就会造成图像在右下角

这个方法最大的缺点就是需要定长宽,有些场景是需要根据内容来进行长宽的延展的,这个方法就不适用了。

如果是不定长宽,可以使用方法 3 translate,忽略掉长宽数值即可,如下:

.father {
/* width: 400px;
height: 200px; */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: yellow;
}

.father 的长宽由内容决定,如图片

<div class="father">
<img src="./测试图片.png" />
</div>

方法 5:绝对定位加上 margin: auto

.father {
width: 500px;
height: 300px;
border: 1px solid #0a3b98;
position: relative;
}
.son {
width: 100px;
height: 40px;
background: #f0a238;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
<div class="father">
<div class="son"></div>
</div>

无论子模块是否有宽高,都可以用 margin:auto 在整个父元素的中间

方法 6: grid 布局

.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: skyblue;

}
.son {
width: 10px;
height: 10px;
border: 1px solid red
}
<div class="father">
<div class="son"></div>
</div>

其实本质跟 flex 布局一样