码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-07-06 20:55:16      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:div   position   osi   宽高   str   orm   垂直   class   bottom   

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;
}

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

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

标签:div   position   osi   宽高   str   orm   垂直   class   bottom   

原文地址:http://www.cnblogs.com/dcyummy/p/7127947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!