Interview Questions

When is auto different from 0 in margin properties?

CSS Interview Questions and Questions

(Continued from previous question...)

107. When is auto different from 0 in margin properties?

In vertical margins, auto is always equal to 0. In horizontal margins, auto is only equal to 0 if the width property is also auto. Here are three examples, assume that there is a <P> that is a child of<BODY>:

Example 1: auto value on the width.

BODY {width: 30em;}
P {width: auto; margin-left: auto; margin-right: auto;}

Since the width property is auto, the auto values of the two margins will be ignored. The result is a P that is 30em wide, with no margins.

Example 2: two auto margins

BODY {width: 30em;}
P {width: 20em; margin-left: auto; margin-right: auto;}

The P will be 20em wide and the remaining 10em will be divided between the two margins. Paragraphs will be indented 5em at both sides.

Example 3: one auto margin

BODY {width: 30em;}
P {width: 20em; margin-left: 2em; margin-right: auto;}

In this case, paragraphs are 20em wide and are idented 2em on the left side. Since the total width available is 30em, that means the right margin will be 8em.
Note that the default value of width is auto, so setting one or both margins to auto is only useful if you set the width to something other than auto at the same time.

(Continued on next question...)

Other Interview Questions