来源: 吾推网  发布时间: 2018-04-09   次浏览
html部分:
<div class="div1">
      <div class="div2"></div>
</div>
css部分:
注意div1和div2宽高是不固定的
方法一:通过把div转换成表格的方式
.div1{
   display: table-cell;
   background:red;
   width:800px;
   height:600px;
   text-align:center;
   vertical-align: middle;
 }
.div2{
   background:yellow;
   width:200px;
   height:200px;
   margin:0 auto
}
方法二:通过绝对定位和CSS3的位移
.div1{
   background:red;
   width:800px;
   height:600px; 
   position:relative
 }
.div2{
   background:yellow;
   width:200px;
   height:200px;
   transform:translate(-50%,-50%);
  -ms-transform:translate(-50%,-50%); /* IE 9 */
  -moz-transform:translate(-50%,-50%); /* Firefox */
  -webkit-transform:translate(-50%,-50%);/* Safari 和 Chrome */
  -o-transform:translate(-50%,-50%); /* Opera */
  position:absolute;
  top:50%;
  left:50%
}
方法三:通过CSS3的盒子模型
.div1{
   background:red;
   width:800px;
   height:600px; 
  display:-webkit-box; 
  -webkit-box-orient:horizontal; 
  -webkit-box-pack:center; 
  -webkit-box-align:center;/* Safari 和 Chrome */其他浏览器前缀同方法二一样,在此省略
 }
.div2{
   background:yellow;
   width:200px;
   height:200px;
}
//标准写法
.div1{
   background:red;
   width:800px;
   height:600px; 
   display:flex; 
   justify-content: center;
   align-items:center;
   flex:1;
 }
.div2{
   background:yellow;
   width:200px;
   height:200px;
}
方法四:通过:after伪类
.div1{
   background:red;
   width:800px;
   height:600px; 
  text-align:center
 }
.div1:after{
    content:"";  
   display: inline-block;  
   vertical-align: middle;  
   height: 100%; 
 }
.div2{
   background:yellow;
   width:200px;
   height:200px;
   display:inline-block;  
   vertical-align: middle;
}

以上方法可能存在兼容性问题,本人只在谷歌浏览器上测试过。