使定位元素居中的4种方法例举

 

例子:

创建两个div,定位父级‘box’  和   定位元素‘sun’。本文要做的是 ‘sun’ 要在 ‘box’ 中居中显示, 该怎么做呢?

定位前效果图

 

 

定位元素居中后的效果图

 

 

 

HTML代码:

 

<!--定位元素父级-->
    <div id="box">
        <!--定位元素-->
        <div id="sun"></div>
    </div>

样式代码:
<style type="text/css">
        /*定位父级*/
        #box{
            width:200px;
            height:110px;
            border:1px solid #000;
            position:relative;
        }

        /*定位元素*/
        #box #sun{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
        }
    </style>

 

 

下面我来依次介绍使定位元素居中的4种方法。

  

方法一:计算定位居中时‘sun’元素的"left", "top" 属性值。

Top属性的值公式:Top属性值 =(‘box’元素的height  – ‘sun’元素的height)÷2;

Left属性的值公式:left属性值 =(‘box’元素的width  – ‘sun’元素的width)÷2;

 

样式代码:

<style type="text/css">

/*定位元素*/
        #box #sun{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
            top:5px;/*(110-100)÷2*/
            left:50px;/*(200-100)÷2*/            
     }

</style>

这种方法需要计算定位元素的"left", "top" 属性值。

 

方法二:计算‘sun’元素的"left", "top" 属性值的百分比。

Top属性的值公式:Top属性值 =(‘box’元素的height  – ‘sun’元素的height)÷2÷‘box’元素的height  ×100%;

Left 属性的值公式:left属性值 =(‘box’元素的width  – ‘sun’元素的width)÷2÷‘box’元素的width×100%;

样式代码:

<style type="text/css">

/*定位元素*/
#box #sun{
             width:100px;
            height:100px;
            background:red;
            position:absolute;
            top:4.5%;/*(110-100)÷2÷110×100%*/
            left:25%;/*(200-100)÷2÷200×100%*/
   }

</style>

这种方法也要需要计算定位元素的"left", "top" 属性值百分比,但是计算方法相对复杂。

 

方法三:设置‘sun’元素的"left", "top" 属性值的百分比都为50%,然后设置margin-left的值为‘sun’元素的宽度一半的负值、设置margin-top的值为‘sun’元素的高度一半的负值。

 

样式代码:

    <style type="text/css">

        /*定位元素*/
        #box #sun{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
            top:50%;
            left:50%;
            margin-top:-50px;/*高度一半的负值*/
            margin-left:-50px;/*宽度一半的负值*/ 
        }

    </style>

这种方法省去了相对复杂的计算过程,但需要知道定位元素的宽高值。

 

方法四:设置‘sun’元素的 "left", "top", "right" 以及 "bottom" 属性值都为0,然后设置‘sun’元素的外边据为:auto

 

样式代码:

    <style type="text/css">

        /*定位元素*/
        #box #sun{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            margin:auto; 
        }

    </style>

这种方法省去了相对复杂的计算过程,也不需要知道定位元素的宽高值。 我把这种方法叫做 ‘万能自适应定位居中’

posted @ 2017-03-10 21:01  林思南  阅读(2719)  评论(0编辑  收藏  举报