垂直居中(笔记)

2016-09-05  本文已影响7人  strong9527

总结一下垂直居中的几种方法。

此博文借鉴了 此篇博文

1 使用绝对定位垂直居中

优点:是适应响应式,且不会添加多余DOM节点。
缺点:不支持IE8及更低版本浏览器


<body>
    <div class="center"></div>
</body>


body,html{
    margin:0;
    height:100%;
}
.center{
    position:absolute;
    margin:auto;
    top:0;
    bottom:0;
    height:200px;
    width:200px;
    left:0;
    right:0;
    background:red;
}

绝对对位原理:元素在过度受限情况下,将margin设置为auto,浏览器会重算margin的值,过度受限指的是同时设置top/bottom与height或者left/right与width。

2.利用transform

优点:是适应响应式,且不会添加多余DOM节点。
缺点:只支持IE9及以上浏览器,低版本IE并不支持。


body,html{
    margin:0;
    height:100%;
}
.center{
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
    height:200px;
    width:200px;
    background:red;
}


此方法的关键就在于利用 transform:translate属性,特别要注意的一点就是此属性的百分比值是指的本元素宽和高的值,而不是父元素

3.利用负的margin来进行定位

优点:兼容性极好低版本IE均支持。
缺点:不支持响应式。


<!-- 在第一个方法的基础上稍加修改 -->

.center{
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-100px;
    margin-top:-100px;
    height:200px;
    width:200px;
    background:red;
}

其实此方法和第二个方法原理基本类似。

4利用表格属性

缺点:增加DOM元素,IE8以下不支持(IE8可以)
优点:很难说吧,虽然说有这么一种方法可以垂直居中,但我无法说服自己用这种方法-_-.....


<body>
    <div class="container"><div class="sss"><div class="center"></div></div></div>
</body>


body,html{
    margin:0;
    height:100%;
    width:100%;
}

.container{
    display:table;
    height:100%;
    text-align:center;
    width:100%;
}

.sss{
    display:table-cell;
    vertical-align:middle;

}
.center{
    width:200px;
    height:200px;
    background:red;
}

5弹性盒式布局

缺点:兼容性简直太差了要到IE11才支持!!,几乎可不用。。。。


<body>
    <div class="center"></div>
</body>


body,html{
    margin:0;
    height:100%;
    width:100%;
}
body{
    display:flex;
    -ms-align-items:center;
    -webkit-align-items:center;
        align-items:center;
    -ms-justify-content: center;
    -webkit-justify-content:center;
        justify-content: center;
}
.center{
    width:200px;
    height:200px;
    background:red;
}


上一篇 下一篇

猜你喜欢

热点阅读