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. User Avatar
    Charlie
    Permalink to comment#

    This doesn’t work on IE…

  2. User Avatar
    Ant

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

  3. User Avatar
    Anonymous
    Permalink to comment#

    So, what do I do with the HTML?

    • User Avatar
      Samar Dhwoj Acharya
      Permalink to comment#

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

    • User Avatar
      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. User Avatar
    Stan
    Permalink to comment#

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

  5. User Avatar
    Alec
    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?

    • User Avatar
      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. User Avatar
    Tomdanme
    Permalink to comment#

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

  7. User Avatar
    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. User Avatar
    Brian FitzGerald
    Permalink to comment#

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

  9. User Avatar
    marcusLAND
    Permalink to comment#

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

  10. User Avatar
    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.

  11. User Avatar
    todd heyman
    Permalink to comment#

    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

    • User Avatar
      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.

    • User Avatar
      Daniel Coates
      Permalink to comment#

      Whoops, I meant higher than the content O.o

  12. User Avatar
    Πόρτες Ασφαλείας
    Permalink to comment#

    Τhank you!

    You can try and with display:inline-block …

  13. User Avatar
    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.

  14. User Avatar
    Nolan
    Permalink to comment#

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

    • User Avatar
      Praveen Kumar

      You can use min-width: 200px; for getting the <div> go not below 200px in width.

  15. User Avatar
    Steve Lack
    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!

  16. User Avatar
    Neer
    Permalink to comment#

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

  17. User Avatar
    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

  18. User Avatar
    gorgono
    Permalink to comment#

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

  19. User Avatar
    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}

  20. User Avatar
    Salman

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

    • User Avatar
      Saeed Alipoor
      Permalink to comment#

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

  21. User Avatar
    VR

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

  22. User Avatar
    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.

  23. User Avatar
    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.

    • User Avatar
      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!

  24. User Avatar
    nand
    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;
    }
    
  25. User Avatar
    gvesch
    Permalink to comment#

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

  26. User Avatar
    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            }
    
  27. User Avatar
    herbyderby
    Permalink to comment#

    Posted in 2009, but still helpful. Thank you!

  28. User Avatar
    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.

  29. User Avatar
    Maliha
    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 =/

  30. User Avatar
    Oh.ComeOn
    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”

  31. User Avatar
    Alec
    Permalink to comment#

    Actually a better implement would be like this:
    .center {
    position: absolute;
    display: block;
    width: 300px;
    height: 300px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    }

    of course do not forget to vendorize it!!!

  32. User Avatar
    Aadil Musavir
    Permalink to comment#

    .links {
    position: absolute;
    margin-left: 120px;
    margin-top: -130px;
    }

    <

    div class=”links” >Worked fine for me at middle of th div </div

  33. User Avatar
    PaulRevival
    Permalink to comment#

    What about this??

    <div class="t">
      <div class="td">
        <div class="target"></div>
      </div>
    </div>
    
    .t {
     display: table;
     table-layout: fixed;
     width: 300px; /* or percentage */
     height: 300px; /* or percentage */
    }
    .td {
     display: table-cell;
     vertical-align: middle;
    }
    .target {
     margin: 0 auto;
    }
    

    OR this for modern browsers:

    <div class="target"></div>
    
    .target {
     position: relative; /* or absolute */
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
    }
    
  34. User Avatar
    james Reegan
    Permalink to comment#

    I’am done four way of ‘Exactly Center position H&V’.
    1. Using Flex, align-items in container.
    2. The item must have margin:auto.

    html, body{
    height: 100%;
    }
    .wrapper{
    display: flex;
    width: 100%;
    height: 100%;
    align-items: center;
    }
    .center{
    width:100px;
    height: 100px;
    background-color: aquamarine;
    margin: auto;
    }

  35. User Avatar
    Gautam Prajapati
    Permalink to comment#

    .center {
    width: 300px;
    height: 300px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform:translate(-50%, -50%);
    }

  36. User Avatar
    kartik patel
    Permalink to comment#

    Its really Helpful sir.. thank you.

  37. User Avatar
    Michael
    Permalink to comment#

    I love you. This just fixed my entire life. May the blessings of the heavens be upon you forever.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag