绝对定位之居中篇

2018-01-30

position:absolute;这个样式我们并不陌生,那么绝对水平/垂直居中呢?


实现绝对水平/垂直居中的方法很简单,只需要margin配合一下就可以


绝对水平居中


1
2
3
<div class="w_father">
<div class="w_son"></div>
</div>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*重置样式*/
html,body,div{
margin: 0;
padding: 0;
}
/*绝对水平居中的方法*/
.w_father{
position: relative;
width: 100px;
height: 100px;
background: gray;
}
.w_son{
position: absolute;
top: 0;
left: 50%;
margin-left: -5px;/*width的负一半*/
width: 10px;
height: 10px;
border-radius: 50%;
background: red;
}


绝对垂直居中

1
2
3
<div class="h_father">
<div class="h_son"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.h_father{
position: relative;
width: 100px;
height: 100px;
background: #ccc;
}
.h_son{
position: absolute;
top: 50%;
left: 0;
margin-top: -10px;/*height的负一半*/
width: 20px;
height: 20px;
background: red;
}