div内元素水平、垂直居中

原始代码:

<div style="float:left;width:200px;height:200px;background:red;">
    <span>aaa</span>
</div>
<div style="float:left;width:200px;height:200px;background:green;">
    <div style="width:50px;height:50px;background:yellow;"></div>
</div>

测试1>>>>>>

外层div增加text-align:center属性,内层元素增加line-height:XXpx属性,高度与外层div高度一致:

<div style="float:left;width:200px;height:200px;background:red;text-align:center;">
    <span style="line-height:200px;">aaa</span>
</div>
<div style="float:left;width:200px;height:200px;background:green;text-align:center;">
    <div style="width:50px;height:50px;background:yellow;line-height:200px;"></div>
</div>

**********************************割割割*******************************************

测试2>>>>>>

外层div增加text-align:center、display:table属性,内层元素增加display:table-cell、vertical-align:middle属性:

<div style="float:left;width:200px;height:200px;background:red;text-align:center;display:table;">
    <span style="display:table-cell;vertical-align:middle;">aaa</span>
</div>
<div style="float:left;width:200px;height:200px;background:green;text-align:center;display:table;">
    <div style="width:50px;height:50px;background:yellow;display:table-cell;vertical-align:middle;"></div>
</div>

**********************************割割割*******************************************

测试3>>>>>>

外层div增加position: relative属性,内层元素增加position: absolute、top: 50%、left: 50%、transform: translate(-50%,-50%)
属性:

<div style="float:left;width:200px;height:200px;background:red;position: relative;">
    <span style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);">aaa</span>
</div>
<div style="float:left;width:200px;height:200px;background:green;position: relative;">
    <div style="width:50px;height:50px;background:yellow;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);"></div>
</div>

**********************************割割割*******************************************

经过上面三种方法的测试,以下几点请大家自行总结:

1、三种方法,对于div内层元素是否为div时的区别;

2、三种方法,对于div的宽高是否为固定值时的区别。

 参考文章:CSS总结div中的内容垂直居中的五种方法 - 风雨后见彩虹 - 博客园

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsdhla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值