How to Center Elements with CSS

Hello,

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~~

In CSS:

.divtocenter {
margin-left:auto;
margin-right:auto;
}

~~2nd way ~~

.divtocenter {
 position:relative;
 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,

Richi

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

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 became a Liaison between Arvixe and Clip-Bucket, so I am here to assist you with anything you need regarding Clip-Bucket or any particular computer-related subject you need. Best Regards, Richi

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 {
    position:relative;
    left:50%;
    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

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


− 1 = 5

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>