<div class="father">
<div class="son"></div>
</div>
1:margin:anto
.father {
background-color: aquamarine;
width: 400px;
height: 400px;
position: relative;
}
.son {
background-color: brown;
width: 200px;
height: 200px;
position: absolute;
margin: auto;
top: 0px;
bottom: 0px;
right: 0px;
left: 0px;
}
- 负margin法
.father {
background-color: aquamarine;
width: 400px;
height: 400px;
position: relative;
}
.son {
background-color: brown;
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px; /* 负height的一半 */
margin-top: -100px; /* 负width的一半 */
}
- transform: translate(-50%, -50%)
.father {
background-color: rgb(183, 201, 195);
width: 400px;
height: 400px;
position: relative;
}
.son {
background-color: rgb(233, 173, 173);
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 弹性盒子:display:flex— CSS3的新属性
align-items:Y轴居中;justify-content:X轴居中
.father {
background-color: rgb(183, 201, 195);
width: 400px;
height: 400px;
display: flex;
align-items: center;
justify-content: center;
}
.son {
background-color: rgb(233, 173, 173);
width: 200px;
height: 200px;
}
- table-cell
table-cell + text-algin
.father {
background-color: rgb(183, 201, 195);
width: 400px;
height: 400px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son {
background-color: rgb(230, 132, 132);
width: 200px;
height: 200px;
display: inline-block;
}
table-cell + margin
.father {
background-color: rgb(183, 201, 195);
width: 400px;
height: 400px;
display: table-cell;
vertical-align: middle;
}
.son {
background-color: rgb(230, 132, 132);
width: 200px;
height: 200px;
margin: 0 autto;
}
- vertical-align: middle ---- 位于父元素的中部:可水平垂直居中文字
.father {
background-color: rgb(183, 201, 195);
width: 400px;
height: 400px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
<div class="father">
<p>我是儿子</p>
</div>