• 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>

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

  • 相关阅读:
    最大子段和(分治法+动态规划法)
    Win11如何重命名音频设备
    Python使用pynput模块后台监控鼠标及按键
    怎么截取视频做gif动图?手把手教你视频在线转gif制作
    猿创征文 第二季| #「笔耕不辍」--生命不息,写作不止#
    牛客·凤凰(https://ac.nowcoder.com/acm/contest/26908/1006)
    ardupilot开发 --- EKF 篇
    springmvc静态资源配置
    编程逻辑入门必备:演绎推理
    java笔试题易错总结
  • 原文地址:https://blog.csdn.net/m0_61643133/article/details/128197586