How to Center Elements with CSS


Having align=”center” deprecated, elements centering is achieved with CSS. There are a couple of ways of doing it, yet I’ll show you two of them. If the first one doesn’t work, the second one will for sure do.

Let’s say we want to have a centered div:

<div class='divtocenter'></div>

~~1st way~~


.divtocenter {

~~2nd way ~~

.divtocenter {
 left:50%; /* or right:50% */

With both ways you get the exact same result. With inheritance of parents’ width, you might get awkward results with one way, but with the other would definitely work.

If you have any questions, or want further explanation, please do not hesitate to contact me and I’ll be more than glad to assist you.

Best Regards,


Owner of Juapo2Services

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , | Posted under Programming/Coding | RSS 2.0

Author Spotlight

Richi González

I started programming when I was 12. I'm a Developer and have been working with the Clip-Bucket script since it came out. I'm the Liaison between Arvixe and Clip-Bucket, so anything you need regarding Clip-Bucket or any particular computer-related subject you need, let me know so I can assist you.

3 Comments on How to Center Elements with CSS

  1. hereNT says:

    Your second example is wrong. It will not center the div. It will put the left or the right corner of the div at the 50% mark of the parent. You have to add a second parameter to it, a negative margin equal to half the total width of the element. So:

    .divtocenter {
    width: 50px;
    margin-left: -25px;

    Also, it will only work on block or inline-block elements.

  2. NASBill says:

    HereNT, Thanks for that info, that cleared things up with the
    margin-left: -25px;
    and putting the amount of half the block in there.
    If Block = 900 then:
    margin-left: -450px;

Leave a Reply to NASBill Cancel reply

Your email address will not be published. Required fields are marked *