Grow your CSS skills. Land your dream job.

How do you center div in CSS?

  • # April 17, 2013 at 4:53 pm

    Hi,
    Was just wondering how other people write the CSS for this.
    http://codepen.io/ghafirsayed/pen/yJzfp

    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 http://codepen.io/ghafirsayed/pen/hjxaH
    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 bydbenjamin.co.uk/comingsoon.php

    # April 17, 2013 at 5:05 pm

    just position it regulary.

    position:relative;top:_px;

    # April 17, 2013 at 5:24 pm

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

    Forked: http://codepen.io/Merri/pen/mBrlw

    # 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: http://codepen.io/ghafirsayed/pen/yJzfp

    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: http://codepen.io/Merri/pen/cdgza

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

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".