以下面的模板为例,通过 CSS 让盒子居中

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            .container {
                background-color: darkorange;
                width: 500px;
                height: 500px;
            }
            .content {
                background-color: cyan;
                width: 200px;
                height: 200px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content"></div>
        </div>
    </body>
</html>

定位布局

.container {
    position: relative;
}
.content {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

定位+移动布局

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

flex 布局

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

grid 布局

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

inline-block 布局

.container {
    text-align: center;
    line-height: 500px;
}
.content {
    display: inline-block;
    vertical-align: middle;
}

table-cell 布局

.container {
    display: table-cell;
    vertical-align: middle;
}
.content {
    margin: auto;
}
最后修改:2021 年 05 月 13 日
你的赞赏是我前进的动力