CSS 如何使DIV层水平居中css
DIV自己没有定义本身居中的属性,html
网上不少的方法都是介绍用上级的text-align: center而后嵌套一层DIV来解决问题.express
但是事实上这样的方法科学吗?网络
通过网络搜索和亲自实验得出如下结论:动画
正确的也是对页面构造没有影响的设置以下:url
对须要水平居中的DIV层添加如下属性:
spa
margin-left: auto; margin-right: auto;
通过这么一番设置问题彷佛解决了,在FF中已经居中了,但是在IE中看居然仍是没有居中!code
问题到底出在哪里呢?xml
若是没有在HTML前加上DTD,那么IE就以HTML而不是XHTML来解释文档.htm
因此,问题并不在CSS而在XHTML网页自己.
须要加上这样的代码才能使得上述设置有效果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
若是您但愿更为严格的XHTML 1.0 Strict或者XHTML 1.1请查阅相关文档.
如何使DIV居中
<!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> <style type="text/css"> body{ margin: 0px; padding:0px; text-align:center; } .container{ /*position:relative;*/ border:1px red solid; margin:0px auto; text-align: left; width:980px; } .head{ margin:auto; text-align:center; width:300px; border:1px red solid; background:lightblue; } .content{ margin:auto; width:300px; border:1px green dotted; background:goldenrod; } </style> <title>3</title> </head> <body> <div class="container"> <div class="head">动画</div> <div class="content"> 经过不透明度的变化来实现全部匹配元素的淡入效果, 经过不透明度的变化来实现全部匹配元素的淡入效果, 经过不透明度的变化来实现全部匹配元素的淡入效果, </div> </div> </body> </html>
主要的样式定义以下:
body {TEXT-ALIGN: center;}
#center { MARGIN-RIGHT: auto; MARGIN-LEFT: auto; }
说明:
首先在父级元素定义TEXT-ALIGN: center;这个的意思就是在父级元素内的内容居中;对于IE这样设定就已经能够了。但在mozilla中不能居中。解决办法就是在子元素定义时候设定时再加上"margin:auto;"或“margin-left: auto;margin-right: auto; ”
须要说明的是,若是你想用这个方法使整个页面要居中,建议不要套在一个DIV里,你能够依次拆出多个div,只
要在每一个拆出的div里定义MARGIN-RIGHT: auto;MARGIN-LEFT: auto; 就能够了。
如何使图片在DIV 中垂直居中,用背景的方法。举例:
body{BACKGROUND: url(http://www.w3cn.org/style/001/logo_w3cn_194x79.gif) #FFF no-repeat center;}
关键就是最后的center,这个参数定义图片的位置。还能够写成“top left”(左上角)或者"bottom right"等,也能够直接写数值"50 30"
如何使文本在DIV中垂直居中
若是是文字,便不能用背景方法,能够用增高行距的办法变通实现垂直居中,完整代码以下:
<html> <head> <style> body{ TEXT-ALIGN: center; } #center{ margin-right: auto; margin-left: auto; height:200px; background:#F00; width:400px; vertical-align:middle; line-height:200px; } </style> </head> <body > <div id="center"><p>test content</p></div> </body> </html>
vertical-align:middle;表示行内垂直居中,咱们将行距增长到和整个DIV同样高line-height:200px;而后插入文字,就垂直居中了。
CSS+DIV控制页面中元素垂直居中代码 全局和区域垂直居中
<style type="text/css" media=screen> body { text-align: center; } #a { width: 200px; height: 400px; background: #000; } #b { margin-top: expression((a.clientHeight-50)/2); width: 50px; height: 50px; background: #FFF; } #c { position: absolute; left: expression((body.clientWidth-50)/2); top: expression((body.clientHeight-50)/2); width: 50px; height: 50px; background: #F00; } </style> <div id="a"> <div id="b"></div> </div> <div id="c"></div>
另外一方法:
<div style="background:blue;position:absolute;left:expression((body.clientWidth-50)/2);top:expression((body.clientHeight-50)/2);width:50;height:50"> </div>