开发者

How do you Horizontally center align a DIV that is absolutely positioned in another DIV?

How do you Horizontally center align a DIV that is absolutely positioned in another DIV ?

HTML

<div style="width:250px;height:250px;background:red;position:relative;">
    <div style="width:开发者_运维百科100px;height:100px;background:blue;position:absolute;"></div>
</div>

Thank You


My answer works only if the background of the inner div has no background color. As your example does, I add a third div. The second one is for the centering, the third one is for the coloring.

<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>

The important thing to notice here is: padding-left:50%;margin-left:-50px;. -50px being half of you div's width.


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

the margin auto should center your div both horizontally and vertically


If you know the sizes of each div and you plan to continue to use position:absolute;, you just set the top and left coordinates. So something like this in the inner div

top:75px; left:75px;

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

*May be off a few px. You may need to adjust.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜