总结几种常见的垂直居中布局

废话不多说,直接看代码!

###1.margin: auto;实现绝对定位元素的水平垂直居中,IE7及以下低版本浏览器不兼容

1
<div class='maps1'></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
* {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
.maps1{
width: 200px;
height: 200px;
background-color: #000;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}

###2. margin的负间距实现绝对定位元素的水平垂直居中,兼容性比较好,比较常用

1
<div class='maps2'></div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
* {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
.maps2{
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
background-color: green;
border: 10px solid #000;
margin: -110px 0 0 -110px;
}

###3.通过transform偏移实现绝对定位元素的水平垂直居中, IE8及以下低版本浏览器不兼容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
* {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
.maps3{
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
background-color: gray;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

###4.CSS3弹性盒模型布局不定宽高实现水平垂直居中 ,CSS3弹性盒模型布局本身就不支持低版本IE6-9浏览器的兼容

1
2
3
<div class="maps4">
<div></div>
</div>

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
35
36
37
body,
html {
height: 100%;
}
* {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
.maps4{
/** height:100%就是让页面撑满整个可视区 */
height: 100%;
/** 流行版弹性盒模型布局 */
display: flex;
display: -webkit-flex;
/** 老安卓版弹性盒模型布局 */
/** display: box;
display: -webkit-box;
/** 老安卓版的横向居中 */
/**box-pack: center;
-webkit-box-pack: center;
/** 老安卓版的垂直居中 */
/**box-align: center;
-webkit-box-align: center;
/** 流行版的横向居中 */
justify-content: center;
-webkit-justify-content: center;
/** 流行版的垂直居中 */
align-items: center;
-webkit-align-items: center;
}
.maps4 div {
width: 100px;
height: 100px;
background-color: black;
}

看代码应该是比较清晰的了,当自己的笔记,不喜勿喷!

访客的ip和所在地址: 访问时间: 当前时间:

殖民 wechat
欢迎您扫一扫上面的微信公众号
打赏不在多少,请鼓励一下!