Usage of margin


I'm confused about the function of "margin".

If a line of code is written like this:
margin: 0 auto;

then what is the function of the number 0?
Is it okay to right both, 0 and 'auto' together?
And what happens when the margin is set to auto? (I kept trying this on the coding page, but nothing seemed to change)

Replace this line with your code.


The values that are provided to the margin rule are processed in different ways depending on how many are provided.

margin: 20px;

If only a single value is provided then ALL of the margins (top, right, bottom, left) are given this value.

margin: 0 auto;

If two values are provided the first value is applied to the top and bottom margins, and the second one applies to the left and right sides.

In the above case, the top and bottom will not have a gap between them and the parent node, and the left and right margins will share the available space effectively centering the element. In order for the centering to work, the element's width must be defined as LESS than the available width. We can talk about this more if you like.

margin: 0 2% 5% 0;

Finally, four values will explicitly define, in order top (0), right (2%), bottom (5%), and left (0). You'll notice they define clockwise starting from the top.

You'll also notice I didn't cover if three values are provided. We never discuss what would happen if only 3 values are provided. I had a friend once who tried, and I haven't seen him or her since...


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.