美文网首页
CSS实现水平垂直居中

CSS实现水平垂直居中

作者: 莣忧草_3b53 | 来源:发表于2020-07-10 12:53 被阅读0次
<div class="wp">
    <div class="box size">123123</div>
</div>

1. absolute + 负margin

.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

2. absolute + margin auto

.box {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

3. absolute + calc

.box {
    position: absolute;;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}

4. absolute + transform

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

5. lineheight

.wp {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.box {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
    text-align: left; /* 修正文字 */
}

6. writing-mode

<div class="wp">
    <div class="wp-inner">
        <div class="box">123123</div>
    </div>
</div>
.wp {
    writing-mode: vertical-lr;
    text-align: center;
}
.wp-inner {
    writing-mode: horizontal-tb;
    display: inline-block;
    text-align: center;
    width: 100%;
}
.box {
    display: inline-block;
    margin: auto;
    text-align: left;
}

7. table

<table>
    <tbody>
        <tr>
            <td class="wp">
                <div class="box">123123</div>
            </td>
        </tr>
    </tbody>
</table>

.wp {
    text-align: center;
}
.box {
    display: inline-block;
}

8. css-table

.wp {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box {
    display: inline-block;
}

9. flex

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

10. grid

.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}

作者:颜海镜
链接:https://juejin.im/post/5b9a4477f265da0ad82bf921
来源:掘金

相关文章

网友评论

      本文标题:CSS实现水平垂直居中

      本文链接:https://www.haomeiwen.com/subject/gzwscktx.html