学习,任何时候开始都不晚!好久没有整理了,简单粗暴上代码

主要目录

方法1:line-height

单行文本垂直居中

1
2
3
4
5
6
7
8
<div>这里是单行文本。</div>
div{
width:100%;
height:30px;
line-height:30px;
text-algin:center;
}

方法2:table-cell

1
2
3
4
5
6
7
8
9
10
<div class="box box1">
<span>垂直居中</span>
</div>
.box1{
display:table-cell;
vertical-algin:middle;
text-algin:center;
}

方法3:display:flex;

1
2
3
4
5
6
.box1{
display:flex;
justify-content:center;
algin-items:center;
}

方法4:absolute与margin

已知盒子宽高

1
2
3
4
5
6
7
8
9
10
11
.box3{position:relative;}
.box3 span{
position: absolute;
width:100px;
height: 50px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-25px;
text-align: center;
}

定位流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div id="wrapper">
<img id="content" src="http://img0.bdstatic.com/img/image/2016ss1.jpg" alt="">
</div>
#wrapper{
position: relative;
width: 800px;
height: 800px;
}
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}

方法5:transform

(推荐移动端常用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#wrapper{
position: relative;
width: 100%;
height:100%;
}
#content {
position: absolute;
top:50%;
left:50%;
width:100%;
transform:translate(-50%,-50%);
text-align: center;
}

方法6:vertical-align

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
26
27
28
29
30
31
32
33
34
<div class="container">
<div class="dialog">
</div>
</div>
.container {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0,0,0,.5);
text-align: center;
font-size: 0;
white-space: nowrap;
overflow: auto;
}
.container:after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.dialog {
display: inline-block;
vertical-align: middle;
text-align: left;
font-size: 14px;
white-space: normal;
}

最后更新: 2018年10月31日 10:59

原始链接: http://irisjiao.github.io/2018/10/30/css/