Rakka Rage
Rakka Rage

Reputation: 19399

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

Upvotes: 2

Views: 179

Answers (2)

Ben Blank
Ben Blank

Reputation: 56572

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

Upvotes: 4

KyleWpppd
KyleWpppd

Reputation: 2030

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

Upvotes: 0

Related Questions