CSS垂直水平居中的方式

HTML結(jié)構(gòu)

<div class="wrap">
   <div class="center">我要居中</div>
</div>

方法一:絕對(duì)定位+margin:auto;

.wrap {
    position: relative;
    width: 250px;
    height: 150px;
    background: pink;
    overflow: hidden;
}
.center {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    /*一定要有寬高*/
    width: 70px;
    height: 50px;
    color: #fff;
    background: deepskyblue;
    margin: auto;
}

方法二:grid布局+justify-content、align-items;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    display: grid;
    justify-content: center;
    align-items: center;
}
.center {
    color: #fff;
    background: deepskyblue;
}

方法三:grid布局+margin;

.wrap 
    width: 250px;
    height: 150px;
    background: pink;
    display: grid;
}
.center {
    color: #fff;
    background: deepskyblue;
    margin: auto;
}

方法四:grid布局+justify-items、align-items;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    display: grid;
    justify-items: center;
    align-items: center;
}
.center {
    color: #fff;
    background: deepskyblue;
}

方法五:flex布局+justify-content、align-items;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    display: flex;
    justify-content: center;
    align-items: center;
}
.center {
    color: #fff;
    background: deepskyblue;
}

方法六:flex布局+margin;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    display: flex;
}
.center {
    color: #fff;
    background: deepskyblue;
    margin:auto;
}

方法七:table-cell布局;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.center {
    color: #fff;
    background: deepskyblue;
    display: inline-block;
}

方法八:絕對(duì)定位+transform;

.wrap {
    position: relative;
    width: 250px;
    height: 150px;
    background: pink;
}
.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    color: #fff;
    background: deepskyblue;
}

方法九:偽元素+line-height;

.wrap {
    width: 250px;
    height: 150px;
    background: pink;
    text-align: center;
}
.wrap::after {
    content: '';
    line-height: 150px;
}
.center {
    color: #fff;
    background: deepskyblue;
    display: inline-block;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容