你如何水平居中对齐绝对位于另一个DIV的DIV?

时间:2011-07-05 11:44:25

标签: css

如何水平居中对齐绝对定位在另一个DIV中的DIV?

HTML

<div style="width:250px;height:250px;background:red;position:relative;">
    <div style="width:100px;height:100px;background:blue;position:absolute;"></div>
</div>

谢谢

3 个答案:

答案 0 :(得分:0)

<div style="width:250px;height:250px;background:red;position:relative;">
    <div style="width:100px;height:100px;background:blue;position:absolute; margin: auto;"></div>
</div>

自动边距应该水平和垂直居中你的div

答案 1 :(得分:0)

如果您知道每个div的尺寸,并且计划继续使用position:absolute;,则只需设置topleft坐标。内部div

就是这样的

top:75px; left:75px;

http://jsfiddle.net/jasongennaro/zQjaU/

*可能会偏离几个px。您可能需要调整。

答案 2 :(得分:0)

仅当内部div的背景没有背景颜色时,我的回答才有效。正如您的示例所示,我添加了第三个div。第二个用于居中,第三个用于着色。

<div style="width:250px;height:250px;background:red;position:relative;">
  <div style="width:100px;height:100px;position:absolute;padding-left:50%;margin-left:-50px">
    <div style="background:blue;padding:0px;"></div>
  </div>
</div>

这里要注意的重要事项是:padding-left:50%;margin-left:-50px;-50px是你宽度的一半。

相关问题