# div 水平垂直居中
html 代码如下
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
1
2
3
4
5
2
3
4
5
# 已知盒子宽高
- 1、将 left right 属性都设为 50%。
- 2、计算元素位置用负 margin 的形式使 div 居中。
.div3 {
width: 520px;
height: 520px;
background: rgb(69, 52, 221);
left: 50%;
top: 50%;
margin-top: -260px;
margin-left: -260px;
position: absolute;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 未知盒子宽高
方法一:
- 1、采用绝对定位
- 2、把 left bottom right top 全设为 0。
- 3、margin 设为 auto
/*方法一: margin:auto; position: absolute; */
.div1 {
width: 520px;
height: 520px;
background: rgb(62, 184, 206);
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;
position: absolute;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
方法二:
- 1、将 left right 属性都设为 50%。
- 2、用 transform: translate(-50%, -50%) 把盒子移动自身的 50% 达到居中的效果。
.div2 {
width: 520px;
height: 520px;
background: rgb(226, 108, 220);
left: 50%;
top: 50%;
position: absolute;
transform: translate(-50%, -50%);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9