CSS:布局 - 水平垂直居中

1. 绝对定位 + 负 Margin

原理:首先利用 absolute 定位把容器块 左顶角 对准浏览器中心,而后再使用 负 margin 把容器块向左移动自身宽度的一半,向上移动自身高度的一半,便可以把容器块的中心移到浏览器中心。css

优势:兼容性好
缺点:须要知道宽高,不够灵活web

.container {
    width: 600px; 
    height: 400px;
    position: absolute; 
    left: 50%; 
    top: 50%;
    margin-left: -300px;    /* 宽度的一半 */
    margin-top: -200px;     /* 高度的一半 */
}

2. 绝对定位 + Transform

原理:首先利用 absolute 定位把容器块 左顶角 对准浏览器中心,而后再使用 CSS3 transform 的 translate(x,y) 把容器块向左(x)移动自身宽度的一半,向上(y)移动自身高度的一半,便可以把容器块的中心移到浏览器中心。浏览器

优势:不须要知道宽高,灵活
缺点,兼容很差,在移动设备上建议使用app

.container {
    width: 600px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); /* 自身尺寸的一半 */
}

3. 绝对定位 + 自动 Margin

原理:浏览器自动计算绝对定位的容器块上下左右外边距。
优势:灵活切兼容性好(IE8+)
缺点:适用于自己有尺寸的元素(好比图片),对于段落等必须显式设置其宽高flex

.container {
    width: 600px;
    height: 400px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

4. CSS3 Flexbox

优势:不须要知道宽高
缺点:兼容性很差,在移动设备上建议使用spa

.container {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    justify-content: center;
    align-items: center;
}

5. Table display

优势:兼容性好
缺点:增长了无用的 HTML 结构code

.vertical-wrapper {
    width: 100%;
    height: 100%;
    display: table;
    .vertical {
        display: table-cell;
        vertical-align: middle;
        & > * {
            vertical-align: middle;
        }
        span {
            display: inline-block;
        }
        img {
            display: inline-block;
        }
    }
    &.center {
        .vertical {
            text-align: center;
        }
    }
}
相关文章
相关标签/搜索