垂直居中

简单列出下列5种方法。

方法0:

思路:绝对定位元素的居中,使用margin: auto
优点:兼容性较好,可以在webkit内核的浏览器中使用
缺点:暂无

    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 200px;
    margin: auto;
    height: 200px;

方法1:

思路:使用css3 flex布局
优点:简单 快捷
缺点:兼容不好吧,详情见:http://caniuse.com/#search=flex

    display: flex;    /* flex实现  垂直水平居中 */
    justify-content: center;
    align-items: center;

方法2:

思路:子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%)
优点:高大上,可以在webkit内核的浏览器中使用
缺点:不支持IE9以下不支持transform属性

    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff;
    transform: translate(-50%, -50%);

方法3:

思路:使用一个空标签span设置他的vertical-align基准线为中间,并且让他为inline-block,宽度为0
缺点:多了一个没用的空标签,display:inline-block IE 6 7是不支持的(添加上:_zoom1;*display:inline)。
当然也可以使用伪元素来代替span标签,不过IE支持也不好,但这是后话了

方法4:

思路:显示设置父元素为:table,子元素为:cell-table,这样就可以使用vertical-align: center,实现水平居中
优点:父元素(parent)可以动态的改变高度(table元素的特性)
缺点:IE8以下不支持

示例代码


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>未知宽高元素水平垂直居中</title>
</head>
<style>

.parent1{
    display: table;
    height:300px;
    width: 300px;
    background-color: #4a4346;
}
.parent1 .child{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    color: #fff;
    font-size: 16px;
}
.parent2{
    height:300px;
    width: 300px;
    text-align: center;
    background: #FD0C70;
}
.parent2 span{
    display: inline-block;;
    width: 0;
    height: 100%;
    vertical-align: middle;
    zoom: 1;/*BFC*/
}
.parent2 .child{
    display: inline-block;
    color: #fff;
    zoom: 1;/*BFC*/
}
.parent3{
    position: relative;
    height:300px;
    width: 300px;
    background: #4a4346;
}
.parent3 .child{
    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff;
    transform: translate(-50%, -50%);   /* 子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%) */
}

.parent4{
    display: flex;    /* flex实现  垂直水平居中 */
    justify-content: center;
    align-items: center;

    width: 300px;
    height:300px;
    background: #FD0C70;
}
.parent4 .child{
    color:#fff;
}
</style>
<body>
    <div class="parent1">
        <div class="child">hello world-1</div>
    </div>

    <div class="parent2">
        <span></span>
        <div class="child">hello world-2</div>
    </div>
    <div class="parent3">
        <div class="child">hello world-3</div>
    </div>
    <div class="parent4">
        <div class="child">hello world-4</div>
    </div>
</body>
</html>

水平居中||垂直居中

可以通过上面的方式拆分去实现,下面以水平居中为例

div 水平居中

margin:0 auto
display: block; // 不是块级元素

// or
display: flex;
justify-content: center;

// or
position: 'absolute',
left: '50%',            
transform: 'translate(-50%, 0)',

附:阮一峰flex语法篇 http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html

results matching ""

    No results matching ""