元素居中的方法
阿新 • • 發佈:2021-01-19
如何讓一個元素在父元素中上下居中?
方法一:給父元素設定成彈性盒子,子元素橫向居中,縱向居中
.container{
background: pink;
height: 200px;
width: 200px;
border: 1px solid #000000;
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background : orange;
}
方法二:父相子絕後,子部分向上移動本身寬度和高度的一半,也可以用transfrom:translate(-50%,-50%)
(最常用方法)
.container{
background: pink;
height: 300px;
width: 300px;
border: 1px solid #000000;
position: relative;
}
.box{
width: 100px;
height: 100px;
background: orange;
position : absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
方法三:父相子絕,子元素所有定位為0,margin
設定auto
自適應
.container{
background: pink;
height: 300px;
width: 300px;
border: 1px solid #000000;
position: relative;
}
.box{
width: 100px;
height: 100px;
background : orange;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}