Quick CSS Trick: How To Center an Object Exactly In The Center

Avatar of Chris Coyier
Chris Coyier on (Updated on )

I recently needed to make a placeholder page for a site. I wanted the logo image to be centered exactly in the middle of the screen, that is, both vertically and horizontally centered. Quickly, I thought I’d just give the image element a class of “centered” and then style that class:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
}

But as I’m sure you are thinking, this doesn’t quite work. What that accomplishes is putting the upper left corner of image exactly in the center of the page, not the center of the image in the center of the page.

not-centered.gif

In order to get the image exactly centered, it’s a simple matter of applying a negative top margin of half the images height, and a negative left margin of half the images width. For this example, like so:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

That will do the trick:

centered.gif

This works wonderfully when you know the size of the thing you are centering. If you don’t know, or are thinking it might change and want to be future proof, try this:

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

The translate value for transform is based off the size of the element, so that will center nicely.