两种方式让DIV上下左右都居中--经测试兼容IE,FF,Opera,Google Chrome
2009-09-22 13:01
681 查看
第一种:全CSS控制,层漂浮(适用于做登陆页面)
代码如下:
第二种:JS + CSS控制,不漂浮(适用于做登陆页面)
代码如下:
最简单适用的一种 上下左右都居中,兼容所有浏览器
<div style="position:absolute; top:50%; height:240px;border:1px solid red; margin:0 auto; margin-top:-120px; width:300px; left:50%; margin-left:-150px;"></div>
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="gb2312" > <head> <title>居中Demo</title> </head> <mce:style type="text/css" title="currentStyle" media="screen"><!-- #divcenter{ position:absolute;/*层漂浮*/ top:50%; left:50%; width:300px; height:300px; margin-top:-150px;/*注意这里必须是DIV高度的一半*/ margin-left:-150px;/*这里是DIV宽度的一半*/ background:yellow; border:1px solid red; } --></mce:style><style type="text/css" title="currentStyle" media="screen" mce_bogus="1">#divcenter{ position:absolute;/*层漂浮*/ top:50%; left:50%; width:300px; height:300px; margin-top:-150px;/*注意这里必须是DIV高度的一半*/ margin-left:-150px;/*这里是DIV宽度的一半*/ background:yellow; border:1px solid red; }</style> </head> <body> <div id="divcenter"> this is a test </div> </body> </html>
第二种:JS + CSS控制,不漂浮(适用于做登陆页面)
代码如下:
<html> <head> <title>DIV居中演示</title> <mce:script type="text/javascript"><!-- function cen(){ var divname = document.all("testdiv"); //居中高度等于页面内容高度减去DIV的高度 除以2 var topvalue = (document.body.clientHeight - divname.clientHeight)/2; divname.style.marginTop = topvalue; } //页面大小发生变化时触发 window.onresize = cen; // --></mce:script> </head> <body style="height:100%; width:100%; text-align:center;" onload=cen()> <div id = "testdiv" name="testdiv" style="margin:0 auto; border:1px solid red; height:400px; width:400px;"> DIV居中演示 </body> </html>
最简单适用的一种 上下左右都居中,兼容所有浏览器
<div style="position:absolute; top:50%; height:240px;border:1px solid red; margin:0 auto; margin-top:-120px; width:300px; left:50%; margin-left:-150px;"></div>
相关文章推荐
- DIV上下左右都居中--经测试兼容IE,FF,Opera,Google Chrome
- JavaScript 无缝上下左右滚动加定高定宽停顿效果(兼容ie/ff)
- div中文字,图片居中对齐,兼容FF、IE
- 纯css完美地解决图片在div内垂直水平居中,兼容IE7.0、IE6.0、IE5.5、IE5.0、FF、
- JavaScript 无缝上下左右滚动加定高定宽停顿效果(兼容ie/ff)
- JavaScript 无缝上下左右滚动加定高定宽停顿效果(兼容ie/ff)
- JavaScript 无缝上下左右滚动加定高定宽停顿效果(兼容ie/ff)
- js文字上下滚动+左右滚动兼容FF/IE
- css中position:fixed实现div居中上下左右居中
- 获取div编辑框,textarea,input text的光标位置 兼容IE,FF和Chrome的方法介绍
- 图片上传预览 兼容 IE 6 7 8 9 FF chrome opera等版本
- 拥有最小高度能自适应高度同时全兼容IE、FF的div设置
- div内部div居中,对内部div设置宽度,再设css样式margin:0 auto(先上下边距,后左右边距)
- jquery 自动收缩浮动在线客服代码,QQ客服、在线MSN、旺旺,兼容IE、 FF、Google Chrome
- [练习]仿迅雷今日看点效果 兼容ie ff opera
- [练习]自定义checkbox效果 兼容ie ff opera
- css:子元素div 上下左右居中方法总结
- js左右伸缩效果(兼容ff/ie)
- css3书签风格按钮列表(兼容ie,ff,chrome,safari和opera) 分类: css3 浏览器兼容 button 按钮 2014-02-12 10:30 338人阅读 评论(0) 收藏
- IE和FF兼容之DIV拖动