首先给父元素写上positon:relative,这么做是为了给子元素打上position:absolute的时候不会被定位到外太空去。接下去,写上子元素的height和width。接着就是整个方法的核心,给子元素再打上top:50%;left:50%以及margin-top:一半的height值的的负数;margin-left:一半的weight值的负数。整理一下之后,可能你会给你的子元素写上这样的css(当然,父元素也要先写上width和height)。
代码如下:
<body style="positon:relative;">
<div style="width:600px;height:300px;position:absolute;top:50%;left:50%;margin-top:-150px;margin-left:-300px;border:1px solid red;">万能的方法。。。</div>
</body>
代码如下:
<body style="positon:relative;">
<div style="width:600px;height:300px;position:absolute;top:50%;left:50%;margin-top:-150px;margin-left:-300px;border:1px solid red;">万能的方法。。。</div>
</body>

本文介绍了一种通过设置CSS样式来实现位置绝对定位元素相对于其父元素中心对齐的方法,包括如何正确使用position、top、left、margin等属性。

1万+

被折叠的 条评论
为什么被折叠?



