Grow your CSS skills. Land your dream job.

Last updated on:

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.

Comments

  1. Charlie
    Permalink to comment#

    This doesn’t work on IE…

  2. Ant

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

  3. Anonymous
    Permalink to comment#

    So, what do I do with the HTML?

    • Seriously I lol’d. Make a div with class center.

    • Loren
      Permalink to comment#

      Don’t try to make this person feel stupid. It’s a reasonable question. When I was learning css it always threw me off when they didn’t have the html listed.

  4. Stan
    Permalink to comment#

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

  5. Permalink to comment#

    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?

    • Pasha
      Permalink to comment#

      I suppose you have found your answer already :)
      But for the other new guys like me, you need to change “position: absolute” to “position: fixed”.

  6. Tomdanme
    Permalink to comment#

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

  7. Poochie
    Permalink to comment#

    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
    Permalink to comment#

    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
    Permalink to comment#

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

  12. Bob Bobson
    Permalink to comment#

    So I had to get a job done in like, 20 minutes. It was horrible, there was fire and brimstone and creatures which even those with the most active imagination could never fathom in their most horrible nightmares. There were bits of CSS everywhere, the HTML looked horrible, but I kept searching for a way, a way to fix this and make it gleam with the power of righteousness and the beauty of the host of heaven.

    Then I found this, and in a single moment, in which you barely had time to blink, everything was fixed, and oh how it was fixed. It was a wonder to behold. You had to shed a tear at how beautiful it looked, the fire subsided, the brimstone turned into those little elephants you can always see dancing their little dance around the edge of your vision, and balance was restored. All was well in the world, thanks to this post.

    Thank you.

  13. thanks so much chris – it works wonderfully – only thing is like marcusLAND said it doesn’t work on iPhone (which in my business is unfortunately how a lot of people check out my work ) – it cuts off the top on mine –

    any fix

    • Daniel Coates
      Permalink to comment#

      You could use media queries to detect the width of the screen and only use the centre trick if the screen is smaller than the height, and use ‘margin: 0 auto;’ for the vertical centre.

    • Daniel Coates
      Permalink to comment#

      Whoops, I meant higher than the content O.o

  14. Τhank you!

    You can try and with display:inline-block …

  15. bern
    Permalink to comment#

    I am having trouble with this as well…
    If I have multiple images of different proportions?
    Also, one of my files has text that would be on the left side of the image, and therefore its dividing the remaining space – from the end of the text – to the right border.

  16. Nolan
    Permalink to comment#

    works great to center the div but i can’t get a minimum width to work. any suggestions? thanks!

  17. Jo
    Permalink to comment#

    Perfect! Thank you!

  18. Permalink to comment#

    I can’t tell you how many times Chris has saved me hours of time and enhanced my reputation with my clients with his great tips and posts. This is another trick that I have to keep relearning every time it comes up. I think think this post has finally solved it for me!

  19. Permalink to comment#

    Its working on IE 9 but having problems in safari..

  20. Permalink to comment#

    Thank you so much for this tip! It has been a real help to me!

  21. Faudzif
    Permalink to comment#

    Thanks dude that is very easy to understand :)

  22. prashanth
    Permalink to comment#

    can u explain me how it works

  23. Ron Strilaeff
    Permalink to comment#

    Chris,

    The implementation is really not that obvious. I think you should show a more complete example:

    what css and html goes with the img tag
    what css and html goes into the containing element

    That way people can play with it and apply it faster to their case.

    Ron

  24. gorgono
    Permalink to comment#

    .content
    {
    width: 600px;
    height: 200px;
    position: fixed;
    left: 50%;
    top: 50%;
    margin-left: -300px;
    margin-top: -100px;
    ;
    }

  25. Michael
    Permalink to comment#

    Fix for the problem of the content disappearing without the option to scroll:

    .content {width: 600px;height: 400px}

    @media only screen and (min-height: 400px) { /the height of your div/
    .content{position: absolute;left: 50%;top: 50%;margin-left: -300px;margin-top: -200px}
    }

    @media only screen and (max-height: 399px) {
    .content {margin-top:10px;margin-bottom:10px} /you can do whatever you want here, this just adds space to the top and bottom to make it seem it is still floating in the middle, but will have scroll/
    }

    and obviously you’ll need this to keep it vertically in center:

    {padding:0; margin: 0 auto}

  26. Salman

    Can anyone show me css-tricks.com footer hover line effects css or js. how it is happening.

    • Saeed Alipoor
      Permalink to comment#

      Just CSS, It’s a span that have horizontal gradient in background+change background-position on hover.

  27. VR

    This method makes a great practice especially during lightboxes popups using js.

  28. Dan

    I find it kind of funny that it was extremely easy to do this 15 years ago with tables and now we can’t do it “correctly” without hacks. If you’re dealing with a variable height div that you want to vertically center an object in, your in for some extra “fun” as well.

  29. Elijah1838
    Permalink to comment#

    Thank you!! I was trying to figure this out for a logo at the top of a page (a

    <

    div class=”logo”> inside of a

    <

    div class=”header”>). I had to tweak it a bit by either changing it to “position: relative;” instead of “position: absolute;” or removing the position element altogether, but it worked!! I’ll definitely remember this neat trick and pass it on.

    • Elijah1838
      Permalink to comment#

      Sorry, never mind… removing the position property altogether did not work (I forgot to save the css style sheet before refreshing… stupid mistake), but making it “relative” still works!

  30. This is super handy. Absolute positioning. Bookmarked and shared.

  31. Permalink to comment#

    This is somewhat wrong. It’s not going to work in all conditions.

    To absolutely center a inline-block level element vertically and horizontally, use the following:

    elm {
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        width: 200px;
        height: 200px;
        margin: auto;
    }
    
  32. gvesch
    Permalink to comment#

    Thanks Chris! I’d been searching for a while when I found this and it worked!

  33. Armend Gashi
    Permalink to comment#

    the easy way you can do it if you make parent position relative and child absolute, then you can just make top,right,bottom,left = 0; and margin: auto;

    8            .container {
      9                width: 600px;
     10                height: 600px;
     11                background: red;
     12                position: relative;
     13                margin: 0 auto;
     14            }
     15            .wrap {
     16                width: 200px;
     17                height: 200px;
     18                position: absolute;
     19                top: 0;
     20                right: 0;
     21                bottom: 0;
     22                left: 0;
     23                background: black;
     24                color: white;
     25                margin: auto;
     26            }
    
  34. herbyderby
    Permalink to comment#

    Posted in 2009, but still helpful. Thank you!

  35. Ancient Code Warrior
    Permalink to comment#

    This is an excellent example of why html + css + javascript + server-side code is such a ridiculous kludge. This wacky paradigm could have been “fixed” a long, long time ago. But instead Microsoft and Netscape had to go to war. It’s been a cluster-ferk ever since. All you script kiddies waste about 95% of your time trying to figure out the most basic issues – instead of writing web apps that actually do something useful. There should have been a single, unified language for the server / browser paradigm. What we have now is pure lunacy.

  36. Permalink to comment#

    After HOURS of trying many things and failing to see result in IE and FF (Chrome was OK), I was totally baffled… I mean, Chris’s method should be the one method that works in all browsers!

    Turns out I totally missed the following at the top of the style.css file:

    html {height: 100%;}

    I feel rather stupid =/

  37. Laura
    Permalink to comment#

    You are awesome! Thank you!

  38. Permalink to comment#

    Lol… Seriously?
    This is not a trick… This is point-blank. Of course that positioning on 50% top/left and then having negative margins half the div’s dimensions makes it centered =))
    But no one has a fixed div nowadays.
    Teaching this is like teaching someone to eat with a spoon… Either they’re 3-4 years old or challenged.

    Here it is:
    HTML:

    <div class="container">
        <span class="helper">
            <img src="my/image.ext" />
        </span>
    </div>
    

    CSS:

            .container {
                position: fixed; // not really necessary
                box-sizing: border-box; // not really necessary
                top: 0; // whatever
                left: 0; // whatever
                width: 100%; // doesn't matter
                height: 100%; // if no height is set, then this container would have it's content's height and you wouldn't have the chance to notice any vertical alignment
                white-space: nowrap; // !important - otherwise, if container is less wide than (.helper width + img width) then img would fall under .helper)
                text-align: center; // to also align the image horizontally
                margin: 0; // doesn't matter
            }
    
            .helper {
                display: inline-block;
                height: 100%;
                vertical-align: middle;
            }
    
            img {
                vertical-align: middle;
                max-height: 90%; // just to leave some some margin.
                max-width: 90%; // just to leave some margin. Or just set it to 100%
            }
    

    This is an image that’s perfectly centered both vertically and horizontally. Of course, you can have a div instead (just tell it it should display: inline-block;)
    And the .container doesn’t have to be fixed or have a height/width set (but no-height set equals to the height of it’s content, so you can’t notice any vertical-alignment). I’m just used to a fixed positioned container because I use this code mainly to center an image on the entire viewport, on top everything else, like in a gallery… for images I add the possibility of “maximizing”

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".