JS元素的水平垂直居中(超级全)面试必背

一.已知宽高

1. 子元素+vertical-align,display: inline-block 父元素+line-height,text-align

 .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      text-align: center;
      line-height: 800px;
    }
 .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      vertical-align: middle;
      display: inline-block;
    } 

2.用定位position, margin: auto; 父元素给relative 子元素给absolute

 .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    }
 .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      margin: auto;
      left: 0;
      bottom: 0;
      right: 0;
      top: 0;
    } 

3.positon+calc函数

.a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    }
.a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      top: calc(50% - 300px / 2);
      left: calc(50% - 300px / 2);
    }

4. position+margin-top+margin-left

  .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    } 
  .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      top: 50%;
      margin-top: -150px;
      left: 50%;
      margin-left: -150px;
    } 

二.宽高未知

1.position+translate

    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      position: relative;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      position: absolute;
      transform: translate(-50%, -50%);
      top: 50%;
      left: 50%;
    } 

2. 弹性盒flex

    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
    } 

3.弹性盒flex-box 子元素margin:auto;

    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: flex;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      margin: auto;
    } 

4.table-cell

    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      display: inline-block;
    } 

猜你喜欢

转载自blog.csdn.net/qq_45279574/article/details/109145307