如何让一个div水平垂直居中

本文探讨了四种不同的CSS方法来在相对定位的父元素(fat)中居中显示绝对定位的子元素(box),分别是:使用`margin: auto`、flexbox布局、transform: translate和百分比坐标。这些技巧有助于理解不同场景下的布局优化。
<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>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值