CSS 垂直居中布局

下面都是我在網(wǎng)上借鑒的方法,親測可用。

<div class="fStyle">  //父元素
  <div class="cStyle"></div> //子元素
</div>

第一種: 定位
規(guī)則如下:
1、父元素為除了static以外的定位方式;
2、子元素為絕對定位,top、bottom、left和right 均設(shè)置為0,margin設(shè)置為
auto。
代碼如下:

.fStyle {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid red;
}
.cStyle {
    position: absolute;
    width: 50px;
    height: 50px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
    border: 1px solid green;
}

第二種: flex布局
規(guī)則如下:align-items實(shí)現(xiàn)垂直居中,justify-content實(shí)現(xiàn)水平居中。
代碼如下:

.fStyle {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    display: flex;
    align-items: center;
    justify-content: center;
}
.cStyle {
    width: 50px;
    height: 50px;
    border: 1px solid green;
}

第三種: table-cell布局
規(guī)則如下:
1、父布局使用vertical-align: middle實(shí)現(xiàn)垂直居中,
2、子布局使用margin: 0 auto實(shí)現(xiàn)水平居中。
代碼如下:

.fStyle{
    width: 100px;
    height: 100px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
}
.cStyle{
    width: 50px;
    height: 50px;
    border: 1px solid green;
    margin: 0 auto;
}

第四種: translate+relative定位
規(guī)則如下:
1、子組件采用relative 定位;
2、top和left偏移各為50%;
3、translate(-50%,-50%) 偏移自身的寬和高的-50%。
代碼如下:

.fStyle {
    width: 100px;
    height: 100px;
    border: 1px solid red;
}
.cStyle {
    width: 50px;
    height: 50px;
    border: 1px solid green;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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