jquery任意不固定大小div水平垂直居中

本文介绍如何使用jQuery在不同浏览器环境下实现网页元素的垂直居中,包括使用位置属性和窗口尺寸变化时的动态调整。
<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
  <title>jquery垂直居中</title>
  <script type="text/javascript" src="jquery.1.6.3.js"></script>
  <script type="text/javascript">
  $(window).resize(function(){
		$(".white_content").css({
			position:'absolute',
			left: ($(window).width() - $('.white_content').outerWidth())/2,
			top: ($(window).height() - $('.white_content').outerHeight())/2 + $(document).scrollTop()
		});
  });
  function show(){
	  document.getElementById('light').style.display='';
	  document.getElementById('fade').style.display='';
	  $(window).resize(); 
  }
  function exit(){
	  document.getElementById('light').style.display='none';
	  document.getElementById('fade').style.display='none';
  }
  </script>
  <style type="text/css">
  *{ margin:0; padding:0;}
  body{font-size:11px; font-family:Verdana, Arial, Helvetica, sans-serif; height: 100%;}
  a{color:#000; text-decoration:none;}
  .img{border:0px;}
  .black_overlay{
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background:#000;
   z-index:1001;
   -moz-opacity: 0.8;
   opacity:.80;
   filter: alpha(opacity=80);
  }
* html {background-image:url(about:blank); background-attachment:fixed; overflow:hidden;}
* html body {width: 100%;  height: 100%; }

  .white_content {
   position: absolute;
   text-align:right;
   width: 500px;
   height: 400px;
   border: 10px solid #ccc;
   background-color: white;
   z-index:1002;
   overflow: auto;
  }
 </style>
 
 
 </head>
<body>
 <p><a href="javascript:void(0);" onclick="show()">展示</a></p>
 
  <div id="light" class="white_content" style="display:none;">
  	<a href="javascript:void(0);" onclick="exit()">关闭</a>
  </div>
  
  <div id="fade" class="black_overlay"  style="display:none;"></div>
 
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值