让一个元素垂直居中是我们开发经常遇到的问题,下述整理各种情况:

div垂直居中

场景设定:让一个50px*50px的Div在一个200px*200px的Div中垂直居中。

元素、文字垂直居中_宽高

<style>
#content {
width: 200px;
height: 200px;
border: 1px dashed #333;
}
#content div{
width: 50px;
height: 50px;
border: 1px solid #f00;
}
</style>
<div id="content">
<div class="mid"></div>
</div>

绝对定位方式

#content {
position: relative;
}
div.mid {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}

设置外边距

div.mid {
position: relative;
top: 50%;
left: 50%;
margin: -25px 0 0 -25px; /*外边距为自身宽高的一半*/
}

未知容器的宽高,利用transform属性

div.mid {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /*向左上角移动25px,25px*/
}

属性

说明

transform

指定应用的变换功能

transform-origin

指定变换的起点(默认元素的中心点)

transform属性值


说明

translate(<长度值,百分数值>)、translateX、translateY

在水平方向、垂直方向或者两个方向上平移元素

scale(<数值>)、scaleX、scaleY

在水平方向、垂直方向或者两个方向上缩放元素

skew(<角度>)、skewX、skewY

在水平方向、垂直方向或者两个方向上使元素倾斜一定的角度

rotate

旋转角度

matrix(4~6个数值,逗号隔开)

指定自定义变换。

transform-origin属性的值


说明

<%>

指定元素x轴或者y轴的起点

<长度值>

指定距离

left、center、right

指定x轴上的位置

top、center、bottom

指定y轴上的位置

通过设置容器的flexbox居中方式

#content {
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}

文字垂直居中

场景设定:让一个50px*50px的Div在一个200px*200px的Div中垂直居中。

元素、文字垂直居中_line-heigh_02

<style>
#content {
width: 200px;
height: 200px;
border: 1px dashed #333;
}
</style>
<div id="content">
<span>垂直居中,哒啦哒啦,就是它</span>
</div>

line-height

#content {
line-height: 200px; /*等于其height*/
}
#content span {
display: inline-block; /*设置为行内块*/
width: 200px;
overflow: hidden; /*防止内容溢出*/
white-space: nowrap;
text-overflow: ellipsis;
}

dispaly:table

#content {
display: table;
}
#content span {
display: table-cell;
vertical-align: middle;
}

上述两者,效果会有所差异