css盒模型居中的 5 种方式

100 阅读1分钟

1.最简单的方法,利用固定定位

父元素设置display:flex,子元素 margin: auto,代码如下:

    .parent {
      width: 300px;
      height: 200px;
      background: rebeccapurple;
      display: flex;
    }
    .child {
      width: 50px;
      height: 50px;
      background: red;
      margin: auto;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

image.png

2.利用定位居中

思路:父级相对定位,子级绝对定位 而四个定位属性的值都设置了0;那么这时候如果子级没有设置宽高,则会被拉开到和父级一样宽高。而现在设置了子级的宽高,所以宽高会按照我们的设置来显示;但是实际上子级的虚拟占位已经撑满了整个父级,这时候再给它一个margin:auto它就可以上下左右都居中了

    .parent {
      width: 300px;
      height: 200px;
      background: pink;
      position: relative;
    }
    .child {
      width: 50px;
      height: 50px;
      background: gold;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

image.png

3.定位配合css3位移

思路:父级相对定位,子级绝对定位,而top,left这两个属性的如果给百分比;那么这个百分比则是相对于父级的宽高来进行计算的;如果只给定这两个值,则子级的右上角会和父级的中心点对齐,得到下图:这时候则需要进一步操作:css3中的位移属性,则是根据自身来计算百分比的;所以只需要利用这个属性把自身再往左上角各移动50%就可以让子级在父级中上下左右都居中了

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: rgb(203, 192, 255);
      position: relative;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rgb(221, 201, 73);
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

1683875797951.jpg

4.[弹性盒]模型

css3的功劳,没啥技巧,掌握了弹性盒模型就能掌握这个方法,简单粗暴。

<style>
    .parent {
      width: 300px;
      height: 200px;
      background: rgb(203, 192, 255);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rgb(62, 57, 24);
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

image.png

5.[网格布局]Grid

这个方法和弹性盒模型一样,简单粗暴,没啥可说的。

    .parent {
      width: 300px;
      height: 200px;
      background:green;
      display: grid;
      justify-content: center;
      align-items: center;
    }
    .child {
      width: 50px;
      height: 50px;
      background: rebeccapurple;
    }
  </style>
  <div class="parent">
    <div class="child"></div>
  </div>

image.png

到此为止,给大家列举了五种元素居中的方法,有任何问题欢迎留言探讨!!!