面试官:水平垂直居中方式有哪些?

120 阅读2分钟

在项目中,我们常常要实现一些元素的水平和垂直居中,下面,我们来总结一下常见的水平垂直居中的方法,我们先来看一下如下代码。

    <div class="container">
        <div class="box"></div>
    </div>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .container{
            width: 400px;
            height: 400px;
            background-color: green;
        }
        .box{
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>

如何让boxcontainer中水平垂直居中呢,我总结了如下的一些方法(初始样式省略),我们先来看看效果

未居中前

image.png

居中之后

image.png

  1. 使用 Flexbox 布局:
.container {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
}
  1. 使用绝对定位和 transform(适用于不知道元素尺寸的情况):
.container {
    position: relative;
}

.box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* 水平垂直居中 */
}
  1. 使用表格布局:
.container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.box {
    display: inline-block; // text-align: center;让行内元素水平居中
}
  1. 使用 inline-block 元素和伪元素(适用于不知道元素尺寸的情况):
.container {
    text-align: center; /* 水平居中 */
}

.container::before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.box {
    display: inline-block;
    vertical-align: middle; /* 垂直居中 */
}
  1. 使用绝对定位和负边距(适用于已知元素尺寸的情况):
.container {
    position: relative;
}

.box {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}
  1. 使用绝对定位和 margin:auto(适用于已知元素尺寸的情况):
.container {
    position: relative;
}

.box {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto; /* 水平垂直居中 */
}
  1. 使用 Flexbox 布局和 margin:auto(适用于已知元素尺寸的情况):
.container {
    display: flex;
}

.box {
    margin: auto; /* 水平垂直居中 */
}
  1. 使用 Grid 布局和 justify-self、align-self 属性(适用于已知元素尺寸的情况):
.container {
    display: grid;
}

.box {
    justify-self: center; /* 水平居中 */
    align-self: center; /* 垂直居中 */
}

这些便是常用的水平垂直居中的方法,希望对大家有所帮助。