Home  >  Article  >  Web Front-end  >  如何将一个绝对定位的div水平垂直居中对齐_html/css_WEB-ITnose

如何将一个绝对定位的div水平垂直居中对齐_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:37:221459browse

如何将一个绝对定位的div垂直居中对齐:
建议:尽可能的手写代码,可以有效的提高学习效率和深度。
在某些时候可能需要将一个绝对定位的div在它的父对象中垂直居中对齐,可能用到的频率不是太高,但是偶尔也会用到,下面就简单介绍一下如何实现此功能。在通常情况下,可以为元素添加margin:0px auto即可让元素在它的父元素水平居中,然后再将它设置为垂直居中对齐即可。但是为绝对定位的对象添加margin:0px auto并不能生效,所以说还是要用老办法实现。
代码示例如下:

<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://www.softwhy.com/" /><title>蚂蚁部落</title> <style type="text/css"> .father{   width:600px;   height:600px;   background-color:green;   margin:0px auto;   position:relative; } .children{   position:absolute;   width:200px;   height:200px;   left:200px;   top:200px;   background-color:red; } </style> </head> <body> <div class="father">   <div class="children"></div> </div> </body> </html>

以上代码可以将子div在父div中水平垂直居中对齐,下面就简单介绍一下几个要点:
1.父元素是使用相对定位,这样子元素就可以以它作为位移参考对象。具体可以参阅CSS的绝对定位 。
2.top属性值计算方式:父元素的高度/2-子元素高度/2,left属性值计算方式:父元素宽度值/2-子元素宽度值/2。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=6952

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn