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

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

它很常见也很简单,但我们常常选择忽略它。本文将为你介绍 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>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值