日期:2014-05-16  浏览次数:20391 次

js 设置div 页面居中


<HTML>
	<HEAD>
		<TITLE>js根据页面大小变化设置div左右居中</TITLE>
	</HEAD>
	<body>
		<div id="" style="border: solid; width: 100%; height: 100px">
			说明:js根据页面大小变化设置div左右居中, 要应用js代码,要设置position:absolute
		</div>
		<div id="mydiv"
			style="border: solid; background-color: red; width: 100px; position: absolute">
			此为居中的div
		</div>
		<!-- <div style="border:solid;height:100px;width:100px">2</div> -->
	</body>
	<script type="text/javascript">
var mydiv = document.getElementById("mydiv");
var mydiv_resize = function() {
	mydiv.style.left = (document.body.clientWidth - 100) / 2;//100为mydiv的宽度
	mydiv.style.height = document.body.clientHeight / 2;
}
mydiv_resize();
window.onresize = mydiv_resize;
</script>
</HTML>