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

HTML:

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

 

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>

 

posted @ 2022-09-30 13:54  bomdeyada  阅读(23)  评论(0编辑  收藏  举报