1、清楚宽高情况下
假设盒子宽高都是400px
方法一:absolute+负margin
width:400px;
height:400px;
position: absolute;
top:50%; //纵轴定位到50%
left:50%; //横轴定位到50%
margin-left:-200px; //向左移自身的一半
margin-top:-200px; //向上移自身的一半
优点:兼容性好
缺点:脱离文档标准流
方法二:absolute+margin:auto
width:400px;
height:400px;
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
优点:兼容性好
缺点:脱离文档标准流
2、不清楚宽高情况下
方法三:absolute+translate
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%); //按照自身的50%向左移动和向上移动
优点:兼容性好
缺点:脱离文档标准流
方法四:flex
//父元素
display: flex;
align-items: center;
justify-content: center;
优点:代码简单
缺点:兼容性较好
方法五:gird
//父元素
display:-ms-grid; //兼容ie
display:grid;
align-items: center;
justify-content: center;
优点:代码简单
缺点:兼容性较好
方法六:table-cell+inline-block
//父元素
display: table-cell;
text-align: center;
vertical-align: middle;
//子元素
display: inline-block;