div内元素水平、垂直居中

  • Post author:
  • Post category:其他


原始代码:

<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中的内容垂直居中的五种方法 – 风雨后见彩虹 – 博客园



版权声明:本文为wsdhla原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。