rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » html/css

css学习笔记:DIV水平垂直居中

无意中看到以前在电脑上保存的一个html页面,关于div水平垂直居中的问题。

css学习笔记:DIV水平垂直居中如何实现div水平垂直居中呢?1.已知宽高度水平垂直居中position:absolute;top:50%;left:50%:将div的左上角水平垂直居中了。在用:margin-top:-(height/2);margin-left:-(width/2) 调整位置达到居中。源码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>已知宽高度DIV垂直水平居 - www.aspxhome.com</title> <style type="text/css"> <!-- .main{ position:absolute; top:50%; left:50%; width:560px; height:188px; margin:-94px 0 0 -280px; background:#C8EDFB} --> </style> </head> <body> <div style="width:950px; margin:0 auto"> <div class="main">已知宽高度DIV垂直水平居</div> </div> </body> </html> [提示:你可先修改部分代码,再按运行]

2.未知高度div水平垂直居中

在一篇贴子中解释到:标准浏览器中(FF,Opera, Safari等):可将父级元素显示方式设定为TABLE(display: table;) ,内部子元素定为table-cell (display: table-cell),通过vertical-align特性使其垂直居中,但非标准浏览器是不支持的。非标准浏览器中:只能在子元素里设距顶部50%,里面再套个元素距顶部-50%来抵消。源码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>未知高度div水平垂直居中 - www.aspxhome.com</title> <style> body { margin:0 auto} body,html{height:100%} #warp {height:100%; overflow:hidden; position:relative;width:100%} #warp[id] {display:table; position:static} #center {position:absolute; top:50%} /* for explorer only*/ #center[id] {display:table-cell; vertical-align:middle; position:static} #main {position:relative; top:-50%;width: 400px;margin:0 auto; background:#BDDCFD} /* for explorer only */ *+html #warp[id]{position:relative} *+html #center[id]{position:absolute} </style> </head> <body> <div id="warp"> <div id="center"> <div id="main">未知高度div水平垂直居中</div> </div> </div> </body> </html> [提示:你可先修改部分代码,再按运行]

顶一下
(0)
踩一下
(0)