div垂值水平居中

286 阅读1分钟

绝对定位

  1. 采用transform: translate(-50%, -50%); 当前父元素添加相对定位
div{
           position: absolute;
           top: 50%;
           left: 50%;
           width: 200px;
           height: 200px;
           transform: translate(-50%, -50%);
           background: red;
        }
2、确定当前div的高度,margin为当前div宽度一半的负值
div{
       position: absolute;
       top: 50%;
       left: 50%;
       width: 200px;
       height: 200px;
       margin-left: -100px;
       margin-top: -100px;
       background: red;
    }
3、绝对定位下,top、left、bottom、right都设置0,margin设置auto
div{
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   background: red;
   width: 200px;
   height: 200px;
   margin: auto;
}

flex布局

.parent{
      height: 800px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #000;
  }
  .child {
      width: 300px;
      height: 300px;
      background: red;
  }

table

table-cell实现水平垂直居中,vertical-align、text-align
.parent {
         display: table-cell;
         vertical-align: middle;
         text-align:center;
         width: 100px;
         height: 100px;
         background: red;
      }
      .child {
          display: inline-block;
      }

calc()函数