推荐三种超好用的div绝对居中的方法

来源:互联网 发布:数据库备份与恢复策略 编辑:程序博客网 时间:2024/06/07 13:51
在实际开发过程中我们经常会遇到div水平、垂直方向绝对居中的布局需求,在开发过程中div布局通过计算宽和高来用margin、padding定位的方式来达到要求,太过繁琐,有时候还因为布局需求,不能给出定高和宽,而达不到要求,今天给大家推荐三种超好用的方法。
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style>.first>.fa{position:relative ;}.first>.fa>.son{position:absolute ;left: 50%;top: 50%;transform: translate(-50%,-50%);}.second>.fa{position:relative ;text-align: center;line-height:225px;}/*行高设置时需要加上子元素高度的一半*/.second>.fa>.son{display: inline-block;}.third>.fa{position:relative ;}.third>.fa>.son{position: absolute;}</style></head><body><p>方法一:css3 手段</p><div class="first"><div class="fa" style="width:200px;height:200px;background:red;"><div class="son" style="width:50px;height:50px;background: yellow;"></div></div></div><p>方法二:display: inline-block;</p><div class="second"><div class="fa" style="width:200px;height:200px;background:red;"><div class="son" style="width:50px;height:50px;background: yellow;"></div></div></div><p>方法三:js手段</p><div class="third"><div id="fu" class="fa" style="width:200px;height:200px;background:red;"><div id="zi" class="son" style="width:50px;height:50px;background: yellow;"></div></div></div></body><script>var fu = document.getElementById("fu");var zi = document.getElementById("zi");zi.style.left=(fu.offsetWidth-zi.offsetWidth)/2+"px";zi.style.top=(fu.offsetHeight-zi.offsetHeight)/2+"px";</script></html>

原创粉丝点击