前端学习笔记 - 元素在父元素居中显示

456 阅读2分钟

在CSS中,让一个元素在父元素中居中显示(如下图),可以通过多种方式实现:

image.png

1. 使用position

通过设置position: absolute、四个边距为0以及margin: atuo,可使元素水平垂直居中。

.outer {
    position: relative;
}

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

⚠️注意,父元素需要设置相对定位,作为子元素定位参考点。

2. 使用margin

通过设置margin的值,可使元素水平垂直居中。

  <style>
.outer {
    height: 200px;
    background-color: lightgreen;
    overflow: auto;
}

.inner {
    width: 200px;
    height: 50px;
    border: 5px solid gray;
    background-color: tomato;
    font-size: 20px;
    margin: 70px auto;
}

⚠️注意,父元素需要设置overflow: auto,否则会引起margin塌陷问题。

3. 使用text-align和line-height(仅限行内元素或行内块元素)

通过设置text-align: centerline-height为高度值,可使元素水平垂直居中。

.outer {
    height: 200px;
    text-align: center;
    line-height: 200px;
}

.inner {
    vertical-align: middle;
    line-height: normal;
}

⚠️注意,子元素需要设置line-height: normal,避免文字被拉伸。

4. 使用position和transform(对行内元素无效)

通过设置position: absolute、上和左边距为50%以及X/Y轴方向位移,可使元素水平垂直居中。

.outer {
    position: relative;
}

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

⚠️注意,父元素需要设置相对定位,作为子元素定位参考点。

5. 使用flex模式

  1. 通过设置父元素display: flex以及主侧轴的对齐方式,可以使元素水平垂直居中。
.outer {
    display: flex;
    justify-content: center;
    align-items: center;
}

⚠️注意,多行情况下侧轴的对齐要使用align-content属性。

  1. 通过设置display: flex以及子元素四个外边距为auto,可以使元素水平垂直居中:
.outer {
    display: flex;
}
.inner {
    margin: auto;
}