如何让一个元素在父元素中上下居中?
方法一:给父元素设置成弹性盒子,子元素横向居中,纵向居中
.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;
}