css水平、垂直居中的各种姿势
2019-05-23 本文已影响0人
myzony
1、第一种
.class {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
}
2、第二种
.class {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
}
3、第三种
.main {
position: relative;
width: 400px;
height: 400px;
margin: 20% auto;
border: 1px solid #c1c1c1;
}
.child {
position: absolute;
/* 垂直居中 */
top: 0;
bottom: 0;
/* 水平居中 */
right: 0;
left: 0;
/* 加上margin:auto */
margin: auto;
width: 200px;
height: 200px;
border: 1px solid red;
}
总结:不考虑兼容性的话三种姿势效果都差不多(区别就是代码多少),考虑兼容性选择后两种,仅供参考。