您的位置:首页 > 其它

元素、文字垂直居中

2017-03-20 10:03 441 查看
让一个元素垂直居中是我们开发经常遇到的问题,下述整理各种情况:


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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


绝对定位方式

#content {
position: relative;
}
div.mid {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11


设置外边距

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


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

div.mid {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /*向左上角移动25px,25px*/
}
1
2
3
4
5
6
1
2
3
4
5
6
属性说明
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;    /* 水平居中 */
}
1
2
3
4
5
1
2
3
4
5


文字垂直居中

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



<style>
#content {
width: 200px;
height: 200px;
border: 1px dashed #333;
}
</style>
<div id="content">
<span>垂直居中,哒啦哒啦,就是它</span>
</div>
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10


line-height

#content {
line-height: 200px; /*等于其height*/
}
#content span {
display: inline-block; /*设置为行内块*/
width: 200px;
overflow: hidden; /*防止内容溢出*/
white-space: nowrap;
text-overflow: ellipsis;
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10


dispaly:table

#content {
display: table;
}
#content span {
display: table-cell;
vertical-align: middle;
}
1
2
3
4
5
6
7
1
2
3
4
5
6
7

上述两者,效果会有所差异
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息