在前端開發(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;
}