频道栏目
首页 > 资讯 > HTML/CSS > 正文

元素居中的几种方法

17-01-19        来源:[db:作者]  
收藏   我要投稿

1,绝对定位的方法

    div{
        width:100px;
        height:100px;
        position:absolute;
        left:50%;
        top:50%;
        margin-left:-50px;
        margin:top:-50px;
    }
这里写图片描述

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

优点:

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

缺点:

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

2,固定定位方法

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

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

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

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

    }

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

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

    div{
        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 div{

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


    <div class="box">
        <div></div>
    </div>

这种方法有其局限性。

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

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

6,针对行内元素

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

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

7,利用css3的属性

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

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

8,利用css3的transform属性

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

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

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

相关TAG标签
上一篇:Neutron源码分析(一)----- RestfulAPI篇
下一篇:系统资源查看
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站