• 06
  • Jan, 06

Using css to center an image with position:absolute

I ran into an interesting problem yesterday while building a simple web page. I needed to cause the main image at the top of the page to do two things: 1) Be centered on a liquid layout page, so that no matter what size the window the image was centered. 2) "Float" above the design on it’s own z-index.

Of course to get the image to be on it’s own layer, it must be set to position:absolute; but once you give it an absolute position it loses all references to being centered.

I thought I had the solution at one point, until I tested it in IE and it was all wrong. After a few hours of struggling, I finally came up with what now seems like a simple solution:

Adding styles to the image itself was my mistake. In this case I had to wrap the image with a div and give it an id. I then applied the following styles to that div in my stylesheet:

#image {
  position:absolute;
  width: 100%;
  text-align: center;
}

The image itself doesn’t need any other styles.

Share and Enjoy:
  • Digg
  • Reddit
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Technorati
  • TwitThis
  • E-mail this story to a friend!

4 Responses

  1. I think you could have alternatively used
    margin: 0 auto;
    not sure if it can be applied directly to an image or not

  2. Thanks for the suggestion Joe. I did try that. It didn’t work.

  3. hi i’m having the same problem but im not familiar with that block of code, could you write it out in full. not your whole page, but the DIV wrapping etc. whatever makes it work. thanks,
    Ros

  4. Thanks, you solved my search!

Leave a Reply

Car Humor | U2 News