How to center the div horizontally and vertically

How to center the div horizontally and vertically

(水平方向)
1.父元素设置: margin:auto
(垂直方向)


1.脱离文档流的居中
.outer{
    
    
    position: relative;
}
.inner{
    
    
    margin: auto;
    position: absolute;
    // 垂直居中
    top: 0;
    bottom: 0;
    // 水平居中
    left: 0;
    right: 0
}

2.margin负值法
.outer{
    
    
    position: relative;
}
.inner{
    
    
    position: absolute;
    top: 50%;
    left: 50%;
    // 垂直居中
    margin-top: -50px;  /*height的一半*/
    // 水平居中
    margin-left: -50px;  /*width的一半*/

    
    transform: translateX(-50%) translateY(-50%);  /* translateX(-50%)水平居中、translateY(-50%)垂直居中*/
}

3.table-cell(未脱离文档流)实现垂直居中
.outer{
    
      // 父元素
    display:table-cell;
    vertical-align: middle;
}

4.利用flex
.outer{
    
    
    display:flex;
    // 水平居中
    justify-content: center;
    // 垂直居中
    align-items: center;
}

Guess you like

Origin blog.csdn.net/weixin_43475142/article/details/114890132