这问题大概分为两种类型,看要求,元素有没有被设置宽高
一、元素被设置了宽高(默认为350px*300px)
1.利用绝对定位
#box{
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
2.先把元素的左上角定位到中央点,在向左和上移动自身宽高的一半(使用margin)
#box{
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -175px;
}
3.先把元素的左上角定位到中央点,在向左和上移动自身宽高的一半(使用transform平移)
#box{
position: fixed;
left: 50%;
top: 50%;
transform: translate(-150px,-175px);
}
4.先把元素的左上角定位到中央点,在向左和上移动自身宽高的一半(使用calc计算)
#box{
position: absolute;
left: 50%;
top: 50%;
top:calc(50% - 150px); /*运算符两边必须有空格*/
left:calc(50% - 175px);
}
4.如果有父元素,可以用flex弹性模型
#father{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
width: 700px;
background-color: aquamarine;
}
二、如果没有固定宽高
1.transform支持百分比
#box{
position: fixd;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
2.如果有父元素,依然可以用flex弹性模型
#father{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
width: 700px;
background-color: aquamarine;
}
3.早期写法,兼容最佳。自动子元素的面积是父元素的四分之一
#box{
width:50%;
height:50%;
background:pink;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
常用的大概就这么多,也许还有我没写出来的,剩下的大家自己发掘。