css水平居中和垂直居中的方法

html

<div class="father">
  <div class="child"></div>
</div>

法一:已知道两个盒子的宽高的情况,可以用margin来居中盒子;

.father{
height: 200px;
width: 200px;
border: 1px solid red;
}
.child{
width: 100px;
height: 100px;
margin-top: 50px;
margin-left:50px ;
border: 1px solid red;
}

法二:在盒子的宽度或者是高度不确定的时候我们就没有办法在像之前的一样去算;

1、可以利用potion 加transfrom :(translate())来居中盒子;

.father{
width: 100%;
height: 400px;
border: 1px solid red;
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 30%;
height:200px;
border: 1px solid red;
}

2、可以利用potion 加margin来居中盒子

.father{
width: 100%;
height: 400px;
border: 1px solid red;
position: relative;
}
.child{
position: absolute;
top:0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 30%;
height:200px;
border: 1px solid red;
}

有不足之处希望大家指正,谢谢!

posted @ 2017-07-06 19:08  dcyummy  阅读(137)  评论(0编辑  收藏  举报