子元素在父元素居中的常用方法-CSS

在前端開發(fā)中,經(jīng)常會遇到子元素需要在父元素居中的情況,而對應(yīng)的css方法也是多種多樣的。子元素在父元素的居中問題也是在面試中經(jīng)常被問到的問題,本文總結(jié)了在日常開發(fā)中最經(jīng)常用到的幾種方法,供大家參考。

1、未知元素大小

  • 1.1 子絕父相布局,top、right、bottom、left都設(shè)為0,margin屬性設(shè)為auto
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin: auto;
    width:200px;
    height:200px;
    background-color:red;
}
  • 1.2 子絕父相布局
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:200px;
    height:200px;
    background-color:red;
}
  • 1.3 使用flex布局
#father{
    display:flex;
    flex-direction:row;
    justify-content:center;
    align-items:center;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    width:200px;
    height:200px;
    background-color:red;
}

2、已知元素大小

  • 2.1 子絕父相布局,top和left設(shè)置50%,margin-left設(shè)置子元素一半寬度的相反數(shù),margin-top設(shè)置子元素高度一半的相反數(shù)
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-100px;
    margin-left:-100px;
    width:200px;
    height:200px;
    background-color:red;
}
  • 2.2 直接計(jì)算出來,margin-top設(shè)置為(父元素高度-子元素高度)/2,margin-left設(shè)置為(父元素寬度-子元素寬度)/2
#father{
    position:relative;
    width:400px;
    height:400px;
    background-color:blue;
}
#child{
    position:absolute;
    margin-top:100px;
    margin-left:100px;
    width:200px;
    height:200px;
    background-color:red;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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