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.

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

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

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! :smiley:

You say p {margin:20px auto 30px;}

top right bottom left

in this case top right/left bottom

Hi TheMockingTurtle. Welcome to the forums. :slight_smile:

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;

{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}.