开发者

center a div absolutely?

I have a div inside another div that has borders on the right and left to center it:

http://jsfiddle.net/Dhvfm/

I want to change the inner div to开发者_StackOverflow中文版 absolute so that the outer div flows up behind it:

http://jsfiddle.net/Dhvfm/1/

Now it's not centered. Is there any way to fix that?


You have two problems here:

  1. You're absolutely positioning an element but not providing top, bottom, left, or right, so it's being left in its original position. Which would be fine, except…
  2. …abolutely-positioned elements with percentage dimensions (width, height) are a percentage of their context parent's outer dimensions (in this case, the <body> element).

You can re-center the inner div by setting left: 0; on it, but it will still overlap the body's borders. To fix that as well, the simplest method is probably to drop the width property in favor of setting both left and right to the width of the body's borders. (This acts as a kind of "smart stretching" for absolutely-positioned elements.)


Edit: This is for horizontal centering...

If you know that your inner div is going to be a set height as you have in your example, you can just calculate the margins. For your example: http://jsfiddle.net/Me7HK/2/

As you can see the margin is (outer height - inner height) / 2

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜