使用三种以上方法实现盒子水平垂直居中

12 阅读1分钟
### 1、子绝父相
<div class="box">
 <div class="box1"></div>
</div>

                        .box {
				position: relative;
				width: 400px;
				height: 400px;
				border: 1px solid red;
			    }

			.box1 {
				position: absolute;
				top: 50%;
				left: 50%;
				width: 100px;
				height: 100px;
				margin-top: -50px;
				margin-left: -50px;
			      	background-color: pink;
			     }  
                             
### 2、位移
.box {
				position: relative;
				width: 400px;
				height: 400px;
				border: 1px solid red;
			}

			.box1 {
				position: absolute;
        移动父盒子的一半
				top: 50%;
				left: 50%;
				width: 100px;
				height: 100px;
        移动自身的一半
				transform: translate(-50%, -50%);
				background-color: pink;
			}
                             
        
### 3、flex
<div class="box">
    <div class="inner"></div>
  </div>
  .box {
      display: flex;
      width: 400px;
      height: 400px;
      border: 1px solid red;
      //设置垂直方向
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .box1 {
      width: 100px;
      height: 100px;
      background-color: pink;
    }
    4、定位
    .box{
      position: relative;
      width: 600px;
      height: 600px;
      background-color: pink;
    }
    .inner{
      position: absolute;
      top:0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }