用CSS实现元素垂直居中方案

  自用笔记:本文属于自用笔记,不做详解,仅供参考。在此记录自己已理解并开始遵循的前端代码规范。What How Why

浮动垂直水平居中

固定长度

margin反向移动

使用position:absolute,设置left、top、margin-left、margin-top的属性
这种方法基本浏览器都能够兼容,不足之处就是需要固定宽高。

1
2
3
4
5
6
7
8
9
10
.one{
position:absolute;
width:200px;
height:200px;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
background:red;
}

fixed

1
2
3
4
5
6
7
8
9
10
.two{
position:fixed;
width:180px;
height:180px;
top:50%;
left:50%;
margin-top:-90px;
margin-left:-90px;
background:orange;
}

大家都知道的position:fixed,IE是不支持这个属性的

宽度自动

自动加清零

1
2
3
4
5
6
7
8
9
10
11
.three{
position:fixed;
width:160px;
height:160px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:pink;
}
1
2
3
4
5
6
7
8
9
10
11
.four{
position:absolute;
width:140px;
height:140px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:black;
}

偏移

使用css3的新属性transform:translate(x,y)属性
这个方法可以不需要设定固定的宽高,在移动端用的会比较多,在移动端css3兼容的比较好

1
2
3
4
5
6
7
8
9
10
11
12
.eight{
position:absolute;
width:80px;
height:80px;
top:50%;
left:50%;
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-ms-transform:translate(-50%,-50%);
background:green;
}

before元素

最高大上的一种,使用:before元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
.nine{
position:fixed;
display:block;
top:0;
right:0;
bottom:0;
left:0;
text-align:center;
background:rgba(0,0,0,.5);
}
.nine:before{
content:'';
display:inline-block;
vertical-align:middle;
height:100%;
}
.nine .content{
display:inline-block;
vertical-align:middle;
width:60px;
height:60px;
line-height:60px;
color:red;
background:yellow;
}

flex

文字居中

文字垂直水平居中

利用display:table-cell属性使内容垂直居中

1
2
3
4
5
6
7
8
.five{
display:table-cell;
vertical-align:middle;
text-align:center;
width:120px;
height:120px;
background:purple;
}

文字垂直水平居中

最简单的一种使行内元素居中的方法,使用line-height属性
这种方法也很实用,比如使文字垂直居中对齐

1
2
3
4
5
6
7
.six{
width:100px;
height:100px;
line-height:100px;
text-align:center;
background:gray;
}

six

文字垂直水平居中

使用css3的display:-webkit-box属性,再设置-webkit-box-pack:center/-webkit-box-align:center

1
2
3
4
5
6
7
8
9
.seven{
width:90px;
height:90px;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
background:yellow;
color:black;
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 浮动垂直水平居中
    1. 1.1. 固定长度
      1. 1.1.1. margin反向移动
      2. 1.1.2. fixed
    2. 1.2. 宽度自动
      1. 1.2.1. 自动加清零
      2. 1.2.2. 偏移
      3. 1.2.3. before元素
      4. 1.2.4. flex
  2. 2. 文字居中
    1. 2.0.1. 文字垂直水平居中
    2. 2.0.2. 文字垂直水平居中
    3. 2.0.3. 文字垂直水平居中
,