首先定义父子级盒子
<style>
.box:hover {
background-color: #ccc;
}
.father {
width: 600px;
height: 900px;
border: 5px solid #000;
}
.box {
width: 300px;
height: 300px;
border: 1px solid #000;
}
</style>
<div class="father">
<div class="box"></div>
</div>
方法1:定位
(推荐)
.father {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法2:flex
(存在兼容性问题)
.father {
display: flex;
justify-content: center;
align-items: center;
}
方法3:单元格
.father {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
方法4:margin
.father {
position: relative;
}
.box {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}