Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS How do you center div in CSS?

  • This topic is empty.
Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #44191
    ghafirsayed
    Member

    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.

    #132190
    Anonymous
    Inactive

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

    #132191
    ghafirsayed
    Member

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

    #132198
    Anonymous
    Inactive

    just position it regulary.

    position:relative;top:_px;

    #132207
    Merri
    Participant

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

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

    #132208
    ghafirsayed
    Member

    Hey thanks Merri never thought of that

    #132213
    CrocoDillon
    Participant

    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 ;)

    #132218
    Merri
    Participant

    Floats also do the same.

    Here are four different tricks for “true” centering: http://codepen.io/Merri/pen/cdgza

Viewing 8 posts - 1 through 8 (of 8 total)
  • The forum ‘CSS’ is closed to new topics and replies.