盒子垂直水平居中的方法

91 阅读1分钟

盒子搭建

<style>
    .box {
      margin: 20px auto;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
    }

    .box1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

image.png

  1. 给父盒子添加相对定位,子盒子绝对定位.再减去盒子自身一半像素
 .box {
      position: relative;
      margin: 20px auto;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
    }

.box1 {
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -50px;
      margin-top: -50px;
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }

2.margin:auto;也是定位的方法,只是定位时用了margin

 .box {
      position: relative;
      margin: 20px auto;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
    }
 .box1 {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }

3.flex布局。display:flex;

 .box {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 20px auto;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
    }

    .box1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }

4.利用位移 transform

 .box {
      position: relative;
      margin: 20px auto;
      width: 500px;
      height: 500px;
      border: 1px solid #000;
    }

    .box1 {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }

完成效果图

image.png