如果不用JavaScript,那么最终效果只有两种方案:
1、div2的宽和高固定:
<div id="div1" style="border-right: thin solid; border-top: thin solid; border-left: thin solid; border-bottom: thin solid; left: 50px; width: 200px; position: absolute; top: 50px; height: 300px;">
<div id="div2" style="border-right: thin dashed; border-top: thin dashed; border-left: thin dashed; border-bottom: thin dashed; left: 50%; width: 100px; position: absolute; top: 50%; height: 100px; margin-left:-50px; margin-top:-50px;">div2在div1中水平方向和垂直方向居中
</div>
</div>
原理很简单:将left和top设置为50%来定位div到浏览器中央,再将margin-left和margin-top值设置为宽和高的一半,使div居中显示。(参考网页地址:
http://tech.idv2.com/2007/07/22/center-div-horizontally-and-vertically-with-css/)
如果div2的宽和高是不确定的,那么就必须用的JavaScript,随时取得div2变化的宽和高中之值,用来改变margin-left和margin-top之值,使得这两个属性值随着宽和高的值动态变化而变化。
2、就是网友杨正祎(阿一)所提供的方法,也是不含有JavaScript的。
我觉得还是方法1较好些!