垂直居中的多种写法

1、垂直居中
//css
.vertical{
    writing-mode: vertical-lr;
    text-align: center;
}
.text{
    writing-mode:initial;
}
//html
this is a test
2、水平居中
//css
.horizontal{
    width:200px;
    height:200px;
    margin:0 auto;
}
//html
3、垂直水平居中

方法1:使用绝对定位

//css
.center-wrap{
    position:relative;
}
.center{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
//若已知宽高,也可用.center-alternative-one或者.center-alternative-two替换.center
.center-alternative-one{
    width:200px;
    height:200px;
    position:absolute;
    top:calc(50% - 100px);
    left:calc(50% - 100px);
}
.center-alternative-two{
    width:200px;
    height:200px;
    position:absolute;
    top:50%;
    left:50%;
    margin-left:-100px;
    margin-top:-100px;
}
//html

方法二:使用display:flex

//css
.center-wrap{
    display:flex;
    align-items: center;
    justify-content: center;
}
//html
this is the box which need be setted
扩展1:

若多个元素需要进行垂直居中,用以下方法可以减少DOM元素的使用:

//css
.box {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        border: 1px solid;
        display: -webkit-flex;
        display: flex;  /* 此处是关键*/
        -webkit-justify-content: center;
        justify-content: center;  /* 此处是关键*/
        -webkit-align-items: center;
        align-items: center;  /* 此处是关键*/
        -webkit-flex-direction: column;
        flex-direction: column;  /* 此处是关键*/
    }
    
    .title {
        font-size: 14px;
        font-weight: normal;
    }
    
    .img {
        width: 200px;
        margin: 20px 0;
    }
    
    .btn {
        width: 100px;
        height: 28px;
        color: #fc6537;
        border-radius: 5px;
        border: 1px solid #fc6537;
        background-color: #fff;
    }

//html
多个元素相对于父元素垂直居中

你可能感兴趣的:(垂直居中的多种写法)