一、利用定位实现
父盒子使用相对定位,子盒子使用绝对定位。
parent {
width: 500px;
height: 500px;
/* 父盒子开启相对定位 */
position: relative;
}
.child {
width: 200px;
height: 200px;
/* 父盒子开启绝对定位 */
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
二、使用定位和margin:auto实现
/* 父盒子设置相对定位 */
.parent {
width: 500px;
height: 500px;
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
三、利用display:table-cell和行内块元素的ext-align: center
.parent {
width: 500px;
height: 500px;
background-color: blanchedalmond;
/* 会使元素表现的类似一个表格中的单元格td,利用这个特性可以实现文字的垂直居中效果 */
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 200px;
height: 200px;
display: inline-block;
}
四、使用flex布局
width: 500px;
height: 500px;
display: flex;
/* 主轴居中 */
justify-content: center;
/* 从轴居中 */
align-items: center;
}
.child {
width: 200px;
height: 200px;
}
五、扩展
利用translate实现
width: 500px;
height: 500px;
background-color: blanchedalmond;
position: relative;
}
.child {
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
margin: auto;
top: 50%;
left: 50%;
/* translate中的%百分比相对的是自身的 也就是向左向上走自身的%50来实现居中效果 */
transform: translate(-50%, -50%);
}