盒子垂直居中的几种方法

盒子垂直居中的几种方法

一、盒子没有固定宽高时

方法一:
.box{
padding: 20px;
background: pink;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

二、盒子有固定宽高时

方法一:
.box{
width:200px;
height:200px;
background: pink;
position: absolute;
top: 0;
left: 0;
bottom:0;
right:0;
margin:auto;
}

方法二:
.box{
width:200px;
height:200px;
background: pink;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}

方法三:
html{
height: 100%;
}
body{
display:flex;
height: 100%;
flex-flow:row wrap;
align-items: center;
justify-content:center;
}
.box{
width:200px;
height:200px;
background: pink;
}

方法四:
通过js,思路:屏幕的宽高-盒子的宽高,最后除以2,获取的值就设置盒子的left/top

你可能感兴趣的:(面试题)