不设置DIV的宽高,让它相对于页面水平垂直居中

一、第一种方法,通过transform实现实现

body,html { margin:0; width:100%; height:100%; }
#box { 
    width:100%; 
    height:100%; 
    background: gray;
    position:relative; 
}
#content{ 
    position:absolute; 
    width:30%; 
    height:30%; 
    background:pink; 
}
.center{
    left:50%; 
    top:50%;  
    transform: translate(-50%, -50%);
    /* transform:translateX(-50%) translateY(-50%);  */
}
<!-- 通过transform实现 -->
    <div id="box">
        <div id="content" class="center">transform只支持IE9以上,IE8及IE8以下都会出现问题。</div>
    </div> 

第二种 、通过display:flex实现,只支持IE10及以上

body,html { margin:0; width:100%; height:100%; }
#box2 { 
    width:100%; 
    height:100%; 
    background: gray;
    display:flex; 
    justify-content:center; 
    align-items: center;
}
#content2 {
    width:30%;
    height:30%; 
    background:pink;
}
<!-- 通过display:flex实现,只支持IE10及以上 -->
    <div id="box2">
        <div id="content2">display:flex;只支持IE10及以上</div>
    </div> 

第三种、通过定位,margin:auto实现,兼容最好

body,html { margin:0; width:100%; height:100%; }
#box3 { 
    width:100%; 
    height:100%; 
    background: gray;
    position:relative;
}
#content3 { 
    width:30%; 
    height:30%; 
    background:pink; 
    position:absolute; 
    top:0; 
    right:0;
    bottom:0;
    left:0; 
    margin:auto; 
}
<!-- 通过margin:auto实现,兼容最好 -->
    <div id="box3">
        <div id="content3">兼容最好,支持到IE8</div>
    </div>

猜你喜欢

转载自www.cnblogs.com/tanweiwei/p/10654159.html