I'm trying to horizontally and vertically center a header on top of an image. So far I've got the vertical centering down (which is the reason for the relative and absolute positioning). However, the horizontal centering is giving me problems now: margin:0 auto; doesn't work, left:50%; doesn't work and text-align:center doesn't work. Does anyone know how to horizontally center the header on top of the image?

Details:

I don't know the height or width of any of the elements, so I can't use fixed heights or widths

Setting the image as a background is not an option because the image is part of the content

Not all headers will be a similar length, so I have to find a dynamic solution (they will all be one line though, I'll cut them off with an ellipsis)

Wow, that's great! Could it also be done with the h2 on top in the html? Because I see it disappears if I change the order. Why is that?
–
user1694077Apr 8 '13 at 18:17

1

I see that z-index fixes that, I don't understand why, but at least I can fix it :)
–
user1694077Apr 8 '13 at 18:19

It's just because of the positioning. It can be done: just set the h2's z-index to something higher, like 1.
–
Alfred XingApr 8 '13 at 18:19

Thanks for the quick answer!
–
user1694077Apr 8 '13 at 18:21

I forgot one thing: I have a div that crops the image when it exceeds the screen width and now the solution doesn't work. I've put it here: jsfiddle.net/kmjRu/30. Do you have an idea how to fix this?
–
user1694077Apr 8 '13 at 18:34