使一个div元素上下左右居中

第一种方法

  • 浮动流自我调节
.box{
widht:200px;
height:200px;
position:relative;
}
.box .son{
width:100px;
height:100px;//给定高度和宽度
position:absolute:
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}

第二种方法

  • flex布局
.div{//父盒子使用flex布局
width:200px;
height:200px;
display:flex;
justify-content:center;
align-item:center;
}

第三种方法

  • 绝对定位+translate //在ios微信里面会造成闪退,说明来自张鑫旭[css世界]
.div{
width:200px;
height:200px;
positon:relative;
}
.div .son{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);//这里的50%为自身宽度和高度的50%
}

猜你喜欢

转载自www.cnblogs.com/shiazhen/p/11864625.html