DIV水平垂直居中 兼容多种浏览器

第一种:全CSS控制,层漂浮(适用于做登陆页面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">

<style type="text/css">
#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控制,不漂浮(适用于做登陆页面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">

	<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;  
	</script>   
  </head>
  
  <body style="height:100%; width:100%; text-align:center;" οnlοad=cen()> 
	<div id = "testdiv" name="testdiv" style="margin:0 auto; border:1px solid red; height:400px; width:400px;">  
	DIV居中演示  
	</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>

 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值