一种让子元素在父元素中居中显示的方法

这种方法利用了外边距margin可以为负的特性。在css定位中将子元素顶部和左边都设置为从父元素的50%处开始定位,然后给子元素的外边距设置负的页边距,数值大小分别为子元素宽和高的一半,这样即可达到子元素在父元素居中显示的目的(如图)。注意使用这种方法子元素的定位方式必须为“相对定位”。

<!DOCTYPE html>
<div id="a">  
    <div id="b"></div>     
</div> 
<style>  
    #a{    
        height: 400px; 
        width: 400px; 
        position: absolute;  
        background: black; 
    }    
    #b{  
        height: 200px;  
        width: 200px;  
        top: 50%;  
        left: 50%;  
        margin: -100px 0 0 -100px;  
        position: relative;   
        background: white;  
    }   
</style>

 

posted @ 2013-01-05 20:55  蔚_Way  阅读(281)  评论(0)    收藏  举报