SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jul 2013
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Margin: auto; Help!

    I have a question on margin: auto; I'm hoping someone can help me understand what's happening... heh.

    Lets say I have a div that contains a p element...

    p {
    height: 50px;
    line-height: 50px;
    margin-top: 20px;
    margin-bottom: 30px;
    }

    div {
    margin-top: 20px;
    padding: 1px;
    }

    div p {
    width: 80%;
    margin-right: auto;
    margin-left: auto;
    }

    This right now centers my p element horizontally inside the div while at the same time giving me 20px of margin-top and 30px of margin-bottom.

    oeE9Mta.jpg

    But if i swap margin-right: auto; and margin-left: auto; to just simply margin: auto...

    div p {
    width: 80%;
    margin: auto;
    }

    OeiNNqy.jpg

    My top and bottom margins vanish. Why? What is auto doing that causes me to lose both my top and bottom margins?

    Would appreciate any help! Thank you!

  2. #2
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    You say p {margin:20px auto 30px;}

    top right bottom left

    in this case top right/left bottom

  3. #3
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,319
    Mentioned
    462 Post(s)
    Tagged
    8 Thread(s)
    Hi TheMockingTurtle. Welcome to the forums.

    margin: auto only centers an element horizontally. Vertical centering has always been trickier. You can do it by setting the container to display: table and the child to display: table-cell; vertical-align: middle;

  4. #4
    SitePoint Mentor bronze trophy
    ronpat's Avatar
    Join Date
    Jun 2012
    Location
    NJ, USA
    Posts
    2,608
    Mentioned
    65 Post(s)
    Tagged
    2 Thread(s)
    {margin:auto;} applies the default "auto" value to all 4 parameters: top, right, bottom, and left; thereby, overwriting/replacing the margin-top and margin-bottom values that you had previously assigned.

    The vertical "auto" value of a paragraph is it's default vertical margin value, which is usually around 1em.

    As already pointed out, when "auto" is applied to margin-left and margin-right of a block object whose width is less than that of its container, it is centered.

    To center the text within a paragraph, you would assign p {text-align:center}.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •