1.给父元素设置display:flex,且align-items:center;justify-content:center;
2.父相对定位+子绝对定位,绝对定位top、left为50%,其余使用margin-left和margin-top移动
3.margin移动 top、left
4.父相对+子绝对,且left、top、bottom、right为0,margin:auto
top,bottom,left,right的值只要两两相等即可,当设置之后,即会与margin中auto自适应,
margin:auto的意思是上下左右都自适应,相匹配即可起作用。
注意:父元素设置为相对定位,子元素设置为绝对定位,以此为前提,
1. top:0;
bottom:0:
margin:auto: //垂直居中
2.left:0;
right:0;
margin:0 auto; //水平居中
3.
2.left:0;
right:0;
margin: auto; //水平居中
4.
top:0;
bottom:0:
left:0;
right:0;
margin:auto; //水平垂直居中
5.
top:0;
bottom:0:
left:0;
right:0;
margin:0 auto; //水平居中
6.margin:0 auto; 无居中
7.margin: auto; 无居中
<section class="pop-win">
<div class="pop-main" id="pop-main"></div>
</section>
.pop-win {
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
background:rgba(0,0,0,0.5);
}
.pop-win div {
position:absolute;
width:400px;
height:200px;
padding:10px;
background: rgba(31,175,0,0.6);
border:1px solid white;
border-radius:6px;
}
/*CSS 水平和垂直居中方法【 1 CSS3】: 将父级元素设为盒子模型,使子元素水平垂直居中。
.pop-win {
display:flex;
justify-content:center;
align-items:center;
} */
/*CSS 水平和垂直居中方法【 2 CSS2】: 将要设置居中的元素分别向 下 和 向 右 各偏移50%,再将margin值设为 负的 元素本身的宽高咸半
.pop-main {
top:50%;
left:50%;
margin-top:-100px;
margin-left:-200px;
}*/
/*CSS 水平和垂直居中方法【 3 CSS3】: 和上面方法2的原理一样
.pop-main {
top:50%;
left:50%;
transform:translate(-50%,-50%);
}*/
/*CSS 水平和垂直居中方法【 4 推荐】:将要设置居中的元素上 、右、下、左 都设为0,再将margin值设为水平垂直居中
.pop-main {
top:0px;
right:0px;
bottom:0px;
left:0px;
margin:auto;
}*/