
行内元素
line-height:内容高度;
tex-align:center;
块级元素
1.定位+margin方法
定位上下左右值为0,然后margin:auto实现
.fa{//父元素设置定位
position: relative;
width: 500px;
height: 500px;
background-color:#eee
}
.son{//子元素设置属性上下左右值为0,margin:auto
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: auto;
width:20px;
height:50px;
background-color:#999;
}
2.定位+margin/tansform方法
子元素在定位下移动父盒子一半宽高,再通过margin操作向反方向移动半个子盒子的宽高
.fa{
position: relative;
width: 500px;
height: 500px;
background-color:#eee
}
.son{
position:absolute;
top:50%;
left:50%;
margin-top: -10px;
margin-left: -25px;
width:20px;
height:50px;
background-color:#999;
}
通过transform:tanslateX()/translateY()反方向移动半个子盒子的宽高实现
.fa{
position: relative;
width: 500px;
height: 500px;
background-color:#eee
}
.son{
position:absolute;
top:50%;
left:50%;
width:20px;
height:50px;
background-color:#999;
transform: translateX(-10px);
transform:translateY(-25px);
}
3.flex方法
父盒子设置flex:flex;设置主轴居中justify-content:center;侧轴居中align-items:center;
.fa{
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color:#eee
}
.son{
width:20px;
height:50px;
background-color:#999;
transform: translateX(-10px);
transform:translateY(-25px);
}
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/114969.html<