A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > CSS > Exactly Center an Image/Div Horizontally and Vertically Submit one!

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.

2 Responses

  1. Charlie says:

    This doesn’t work on IE…

  2. Ant says:

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

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.