如何实现水平垂直居中?

实现居中效果的方法:
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;
        }

你可能感兴趣的:(如何实现水平垂直居中?)