CSS 垂直居中

CSS 垂直居中

有固定的高度和宽度

主要是依靠 absolute 属性置于距离左上角 50% 的位置,然后再利用 margin 调整位置。

.parent {
    position: relative;
}

.child {
    width: 300px;
    height: 100px;
    padding: 20px;

    position: absolute;
    top: 50%;
    left: 50%;

    margin: -70px 0 0 -170px;
}

效果如下

假如不添加 margin

无固定的高度和宽度

使用 transform 属性:

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

使用 flexbox 布局

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}
  • justify-content: center:水平居中
  • align-items: center:垂直居中

单行文本水平垂直居中

transform

.container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

Flexbox

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

table-cell

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

.parent > .child {
    display: table-cell;
    vertical-align: middle;
}

absolute

.container {
    position: relative;
    text-align: center;
}

.container > p {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin-top: -9px;
}

line-height (不推荐)

.parent {
    height: 200px;
    width: 400px;
    text-align: center;
}

.parent > .child {
    line-height: 200px;
}

多行文本水平垂直居中

参考