css 元素居中布局的几种方式

<div class='box1'>
    <div class='box2'></div>
</div>

1,使用 display: table-cell

<style>
    .box1 {
        width: 500px;
        height: 500px;
        border: 1px solid red;
        /* 关键代码 */
        display: table-cell;
        vertical-align: middle;
    }
    .box2 {
        width: 100px;
        height: 100px;
        background: green;
        /* 关键代码 */
        margin: auto;
    }
</style>

2,使用【定位】居中

1vw 为当前页面 viewport 宽度的 1/100

.box1 {
    position: relative;
    height: 90vw;
    width: 90vw;
    margin: 0;
    border: 1px solid gray;
}
.box2 {
    position: absolute;    /* 相对父容器绝对定位 */
    top: 45vw;             /* top 设置为父容器高度的一半 */
    left: 45vw;            /* left 设置为父容器宽度的一半 */
    margin-top: -30px;     /* margin-top 设置为自己高度的负一半 */
    margin-left: -30px;    /* margin-left 设置为自己宽度的负一半 */
    width: 60px;
    height: 60px;
    background-color: gray
}

3,使用【flex布局】居中

.box1 {
    height: 100px;
    display: flex;           /* 设置父容器为 flex 布局 */
    border: 1px solid gray;
}
.box2 {
    width: 60px;
    height: 60px;
    bacckground-color: gray;
    margin: auto;            /* 设置子项的 margin 为 auto 时,会自动居中 */
}

猜你喜欢

转载自blog.csdn.net/M_wolf/article/details/81352140