Code Snippet

Home » Code Snippets » CSS » Exactly Center an Image/Div Horizontally and Vertically

Exactly Center an Image/Div Horizontally and Vertically

.center {
   width: 300px;
   height: 300px;
   position: absolute;
   left: 50%;
   top: 50%;
   margin-left: -150px;
   margin-top: -150px;
}

Negative margins are exactly half the height and width, which pull the element back into perfect center. Only works with elements of a fixed height/width.

Subscribe to The Thread

  1. Charlie

    This doesn’t work on IE…

  2. I’d use display:inline-block for that. Works much better (dynamic vertical and horizontal dimersions for both container and content).

  3. Anonymous

    So, what do I do with the HTML?

  4. Stan

    Excellent, thank you. No troubles here.. works well in IE, FF, etc.

  5. Ugh! I’m really having trouble getting a popup div to center vertically on mobile devices. When I’m scrolled half way down the screen and click the link button, the popup appears up top where I cannot see it. Any suggestions?

  6. Tomdanme

    Cool! This is just what I was looking for (I’m not lying.)!

  7. Poochie

    I’ve been using this, but… let’s say you resize your window to like 100px wide. Then content starts to get cut off on the left side and you can’t scroll to it. Is there a fix for this?

  8. Thanks you. But I am just beginning of web design.

  9. Andrew Roberts

    Thanks Chris, works perfect for me! :)

  10. Very nice solution. This helped me center a “loading” image within a fluid width container. Worked like a charm.

  11. marcusLAND

    this doesn’t work on iOS, but all good for cross browsers for me…why?!?

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~