水平居中的四种方式

137 阅读1分钟
  • 利用子绝父相定位的方式来实现
#container{
width:500px;
height:500px;
position:relative;
}

#center{
width:100px;
hight:100px;
position: absolute;
top: 50%;
left: 50%;
margin-top:-50px;
margin-left:-50px;
}
  • 绝对定位第二种方式
#container{
width:500px;
height:500px;
position:relative;
}

#center{
width:100px;
hight:100px;
position: absolute;
top: 0;
left: 0;
bottom0right0margin:auto;
}
  • 利用Css3的transform,可以轻松的在未知元素的高宽的情况下实现元素的垂直居中
#container{
position:relative;
}

#center{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
  • flex
#container{
display:flex;
justify-content:center;
align-items: center;
}