例如有一个父子div如下:

    <div class="parent">
      <div class="child"></div>
    </div>

如何实现图示效果呢:

首先初始化一下css便于展示效果:

    .parent { 
      width: 500px;
      height: 500px;
      background: #ffd700;
    }
    .child { 
      width: 100px;
      height: 100px;
      background: #9400d3;
    }

方法1:相对定位和绝对定位的搭配使用(常用方法)

    .parent { 
      position: relative;
    }
    .child { 
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -25px;
      margin-left: -25px;
    }

将父盒子设置为相对定位,子盒子设置为绝对定位,进行定位,需要注意的是定位中心是子盒子的左上顶点,所以需要减去盒子的一半的像素,即回退一半的距离。

方法2:flex布局(父元素指定子元素居中)

    .parent { 
      display: flex;
      justify-content: center;
      align-items: center;
    }

直接将父盒子设置为flex布局方式,然后利用flex最为常用的两个属性justify-content:center与align-items:center变可以实现其子盒子水平垂直居中。

方法3:极简实现,最佳方案,只需要考虑flex!

    .parent { 
      display: flex;
    }
    .child { 
      margin: auto;
    }

方法3是方法2的另一种实现,都是利用flex布局技巧,子盒子的margin属性设为auto变可以自动实现居中效果。

附加一问:如何水平居中一个元素?

答:
①如果需要居中的元素为 inline 或 inline-block,为父元素设置 text-align: center;即可实现

②如果要居中的元素为一个块级元素的话,一般使用 margin: 0 auto; 进行居中。

本文地址:https://blog.csdn.net/qq_43464088/article/details/112549827