1. 定位方法
.child{
width: 200px;
height: 200px;
position: absolute;
background: #000;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
2.基于定位和位移
.content{
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
background: #000;
}
3.基于定位和margin负值
.content{
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left:-100px;
margin-top:-100px;
background: #000;
}
4.flex布局方法,也是几种方法中最优的办法,定位可能会影响到结构布局。
.wrapper{
width: 500px;
height: 500px;
display: -webkit-box; //felx兼容写法
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
也可以这样写
.wrapper{
width: 500px;
height: 500px;
display: -webkit-box;
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: flex;
}
.content{
width: 200px;
height: 200px;
margin: auto;
background: #000;
}
参考文献:https://caniuse.com/#search=flex
https://blog.youkuaiyun.com/freshlover/article/details/11579669