如何實現水平垂直居中?

wang_qiu_shuang發表於2020-10-10

實現居中效果的方法:
1、用absolute + 負margin

father{
>           position: relative;//父元素設定絕對定位
>       }
>       .son{
>           position: absolute;
>           width:100px;
     		height:100px;
>           top: 50%;
>           left: 50%;
>           margin-left: -50px;
>           margin-top: -50px;
>       }

2、absolute + margin auto

.father{
          position: relative;//父元素設定絕對定位
      }
      .son{
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          margin: auto;
      }

3、absolute + transform

.father{
          position: relative;//父元素設定絕對定位
      }
      .son{
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
      }

4、absolute + calc,

.father{
          position: relative;//父元素設定絕對定位
      }
      .son{
          position: absolute;
          width:100px;
     	  height:100px;
          top: calc(50%-50px);
          left: calc(50%-50px);
      }

5、flex佈局

.father{
        display: flex;
        justify-content: center; /*顯示在主軸的中間*/
        align-items: center; /*子項在側軸中間位置*/
    }

6、grid佈局

.father{
    display:grid;
    align-items:center;
    justify-items:center;
}

7、css新增的table屬性

.father {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    .son {
        display: inline-block;
    }

8、text-align和line-height

.father{
            text-align: center;
            width: 100px;
            height: 100px;
            background: indianred;
            line-height: 100px;
        }

相關文章