天天看点

8 种实现垂直和水平居中元素的方法汇总

8 种实现垂直和水平居中元素的方法汇总

英文 | https://blog.bitsrc.io/8-ways-to-center-elements-vertically-and-horizontally-3dc8cce047d8

在前端网络面试中,你可能遇到过“如何使元素垂直和水平居中?”的问题。不止一次。

它很常见也很简单,但我们常常选择忽略它。本文将为你介绍 8 种实现方式。

首先看示例 HTML:

<div class="parent" style="background: black; width: 200px; height: 200px">
  <div class="child" style="background: red; width: 100px; height: 100px"></div>
</div>      

我们得到一个 200px 的父容器和一个 100px 的子容器。

下面我将介绍8种方式,最后给出一个运行示例。

1.

首先是基于父子容器大小的粗略 CSS 值:

<style>
  .parent {
    position: relative;
  }
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px;
  }
</style>      

一旦原始元素大小发生变化,CSS 就需要随之改变。这并不理想。所以下面介绍的方法不需要考虑父子元素的宽高,比较推荐。

2.

<style>
  .parent {
    position: relative;
  }
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
</style>      

这种方法与第一种方法的不同之处在于我们使用了transform而不是margin,这使得我们的CSS代码不再依赖于元素的尺寸。

3.

<style>
  .parent {
    position: relative;
  }
.child {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
</style>      

请记住,所有四个方向的值都必须为 0。

4.

<style>
  .parent {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }
.child {
    display: inline-block;
  }
</style>      

5.

<style>
  .parent {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>      

这种方法可能是目前使用最广泛的。

6.

<style>
  .parent {
    display: flex;
  }
.child {
    margin: auto;
  }
</style>      

7.

<style>
  .parent {
    display: grid;
    /* The following 3 ways of writing are OK */
    /* 1 */
    /* justify-content: center;
    align-content: center; */
/* 2 */
    /* align-items: center;
    justify-items: center; */
/* 3 */
    place-content: center;
  }
</style>      

8.

<style>
  .parent {
    display: grid;
  }
.child {
    align-self: center;
    justify-self: center;
  }
</style>      

到目前为止我看到的就是这些,但我相信还有其他方法,欢迎你在留言区分享更多的方法,最后感谢你的阅读。

x

8 种实现垂直和水平居中元素的方法汇总