<div class=“box”></div>
第一种:已知宽高。给元素设置绝对定位,left和top设为50%,margin-left设为负的自身宽度的一半,margin-top设为负的自身高度的一半。
.box{
width: 200px;
height: 200px;
background: skyblue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
第二种:宽高不固定。给元素设置绝对定位,left和top设为50%,用变换中的位移在x轴上向左移动自身宽度的一半,在y轴上向上移动自身高度的一半。
.box{
width: 20%;
height: 20%;
background: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
第三种:宽高固定和不固定都适用。给元素设置绝对定位,把left,right,top,bottom都设置为0,margin设置为auto。
.box{
width: 20%;
height: 20%;
background: orange;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
第四种:宽高固定和不固定都适用。把html和body的高度设为视口的高度。把body变为伸缩容器(伸缩项目的父元素是body,也可能不是)。给伸缩容器设置主轴,侧轴居中对齐。
html,body{
height: 100%;
}
body{
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 20%;
height: 20%;
background: blue;
}
第五种:宽高固定和不固定都适用。把html和body的高度设为视口的高度。把body变为伸缩容器(伸缩项目的父元素是body,也可能不是)。给伸缩项目设置margin: auto;。
html,body{
height: 100%;
}
body{
display: flex;
}
.box{
width: 200px;
height: 200px;
background: darkmagenta;
margin: auto;
}