Get a free trial // Grow your CSS skills // Land your dream job

How do you center div in CSS?

  • # April 17, 2013 at 4:53 pm

    Was just wondering how other people write the CSS for this.

    If you have a div lets say 500px*200px and you want to center another div(480px*180px) inside it and you want to set all margins (top, right, bottom, left) equal (margin:10px;).
    How do you do it? If we give margin-top/padding-top to the inner div it brings the whole container down(which we dont want) but still doesn’t get centered.

    I do it by either of these ways:
    1- Give a 1px border-top to the outer div of same color(div backgd color) and then give margin-top to the inner div.
    like this
    2. Give position relative to the outerdiv and set the inner div by giving it position absolute.
    I m sure people must be doing better than this . What do you do to handle such situtations.

    # April 17, 2013 at 4:56 pm

    margin:0 auto;
    centers the child div according to the parent div.

    # April 17, 2013 at 4:57 pm

    That will only center the div from right and left how about top and bottom?

    # April 17, 2013 at 5:02 pm

    That requires 3 divs.

    # April 17, 2013 at 5:03 pm

    Here is an example

    # April 17, 2013 at 5:05 pm

    just position it regulary.


    # April 17, 2013 at 5:24 pm

    Instead of margin in the child element use padding in the parent element.


    # April 17, 2013 at 5:31 pm

    Hey thanks Merri never thought of that

    # April 17, 2013 at 5:49 pm

    In your first pen:

    You could have given `#banner` it’s own block formatting context by setting `overflow: hidden;` or `display: inline-block;`, that would prevent margin-collapsing from `#banner_inner` to `#banner`. For future reference when setting padding on parent is not possible ;)

    # April 17, 2013 at 6:23 pm

    Floats also do the same.

    Here are four different tricks for “true” centering:

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed