div垂直,水平居中

方法一:用display:table 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.parent {
display: table;
height: 300px;
background: yellow;
}
.child {
display: table-cell;
vertical-align: middle;
background: red;
}

.content {
width: 50px;
margin: auto;
background: blue;
}

HTML

1
2
3
4
5
<div class="parent">
<div class="child">
<div class="content">XXX</div>
</div>
</div>
## 方法二:用position:absolute
1
2
3
<div class="parent">
<div class="box"><img src="cat.jpg" alt=" /></div>
</div>

先用浏览器看一下效果如下:

使用css语法来调整位置

1
2
3
4
5
6
7
8
9
10
11
12
.parent{
width: 500px;
height: 500px;
position: relative;
background-color: gray;
}
.box{
width: 233px;
position: absolute;
left: 50%;
top: 50%;
}

我们设置的位置是 left:50%; 和 top:50%; 刚好就是中心位置,因为 CSS 的 position:absolute; 是以 div 的左上角当作计算点,所以才会产生这样的结果,如下图:

接下来再让div.box 左、上移一半的宽度、高度就可以了

1
2
3
4
5
6
7
8
.box{
width: 233px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -116px;
margin-top: -99px;
}

欢迎关注我的其它发布渠道