CSS Centering Trick: How to center a div or an image?

Posted by Stanislav Furman  on February 15, 2012

From time to time we create HTML/CSS templates where we need to center a div or an image. For some newbies it poses a problem. In this blog post I'll show you one of the ways of CSS centering.

Suppose you have a div or an image (with the size 150px X 100px) that should be centered on the web page. First step you do is the following CSS:


centered {
  position:  fixed;
  top:  50%;
  left:  50%;
}

CSS Centering Trick (image 1)

Now we just need to to move the block up and left for a half of the block's size:


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

CSS Centering Trick (image 2)

And voila! Here is your block centered on a page using this nice CSS trick.

Have fun!

 


Comments

Rodion says:
May 1, 2014 at 12:54 am
Good one!
However second image has a small glitch whereas top should read (-50px) and left (-75px) ;-)
Flag as SPAM  |  Permalink

Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.