您现在的位置:首页 >> 前端 >> 内容

元素居中的几种方法

时间:2017/1/19 10:45:00 点击:

  核心提示:1,绝对定位的方法p{width:100px;height:100px;position:absolute;left:50%;top:50%;margin-left:-50px;margin:top:...

1,绝对定位的方法

    p{
        width:100px;
        height:100px;
        position:absolute;
        left:50%;
        top:50%;
        margin-left:-50px;
        margin:top:-50px;
    }
元素居中的几种方法

结果如上图所示。可以实现在父容器内的居中效果。

优点:

1,所有的浏览器都是支持的。

缺点:

其必须是固定宽高的,其宽高是不可以变得。适用范围比较窄。

2,固定定位方法

    p{
        width:100px;
        height:100px;
        position:fixed;
        left:50%;
        top:50%;
        margin-left:-50px;
        margin:top:-50px;
    }

这种实现的方法和第一种方法思路是一样的。优缺点也是一样的。

3,绝对定位加margin:auto实现

    p{
        position:absolute;
        width:100px;
        height:100px;
        margin:auto;
        left:0;
        top:0;
        right:0;
        bottom:0;

    }

这种实现方式比较灵活。但其在ie低版本的时候是不支持的。在标准的浏览器下,可以随意使用。

4,固定定位加margin:auto实现

    p{
        position:fixed;
        width:100px;
        height:100px;
        margin:auto;
        left:0;
        top:0;
        right:0;
        bottom:0;

    }   

同样的将决定定位换成固定定位,也是可以实现的。

5,table-cell实现

    .box{
        width: 300px;
        height: 300px;

        display: table-cell;
        vertical-align: middle;
        text-align: center;
        border:1px solid #000;
    }
    .box p{

        width:100px;
        height:100px;
        margin 0 auto;
        background-color: red;
    }


    <p class="box">
        <p></p>
    </p>

这种方法有其局限性。

1,其父元素或子元素不可以出现浮动。

2,子元素是行内元素的时候可以不加”margin:0 auto;”这一句。如果是块级元素,就必须要加这一句代码。

6,针对行内元素

    p{
        height:100px;
        text-align:center;
        line-height:100px;
    }

这种只针对行内元素有效。

7,利用css3的属性

    p{
        display:flex;
        justify-content:center;
        align-items:center;
    }

这种是利用css3的弹性盒模型。优点是简单,适用性广。缺点是低版本的浏览器不支持。

8,利用css3的transform属性

    .box {
        width: 300px;
        height: 300px;

        position: relative;
    }
    .box p{
        width: 100px;
        height: 100px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        background-color: red;
    }
    <p class="box">
        <p></p>
    </p>

其实这种和第一种的原理是一样的。但比第一种的局限性小很多。缺点就是低版本的浏览器是不支持的。

作者:网络 来源:alitterboy