<div class="fat">
<div class="box"><div/>
</div>
1.第一种
<style>
.fat{
width:200px;
height:200px;
border:1px solid red;
position:relative
}
.box{
width:50px;
height:50px;
top:0;
left:0;
bottom:0;
right:0;
position:absolute;
margin:auto;
background:black
}
</style>
2.第二种:
<style>
.fat{
width:200px;
height:200px;
border:1px solid red;
display:flex;
align-item:center;
justify-content:center;
}
.box{
width:50px;
height:50px;
background:black
}
</style>
3.第三种
<style>
.fat{
width:200px;
height:200px;
border:1px solid red;
position:relative
}
.box{
width:50px;
height:50px;
background:black;
top:50%;
left:50%
tranform:translate(-50%,-50%)
}
</style>
4:第四种
<style>
.fat{
width:200px;
height:200px;
border:1px solid red;
position:relative
}
.box{
width:50px;
height:50px;
background:black;
left:calc((200px - 50px)/2);
top:calc((200px - 50px)/2)
}
</style>
本文探讨了四种不同的CSS方法来在相对定位的父元素(fat)中居中显示绝对定位的子元素(box),分别是:使用`margin: auto`、flexbox布局、transform: translate和百分比坐标。这些技巧有助于理解不同场景下的布局优化。
570

被折叠的 条评论
为什么被折叠?



