How to horizontally center a header that is position:absolute

sherriotter

New Member
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: \[code\]margin:0 auto;\[/code\] doesn't work, \[code\]left:50%;\[/code\] doesn't work and \[code\]text-align:center\[/code\] 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)
HTML\[code\]<article> <h2>Title</h2> <img src="http://bit.ly/gUKbAE" /></article>\[/code\]CSS\[code\]article { position: relative; }h2 { line-height: 0; position: absolute; top: 50%; left: 0; margin: 0; padding: 0;}\[/code\]It's here: http://jsfiddle.net/kmjRu/21/
 
Top