CSS padding and margin

Padding and margin often cause misunderstandings.

<div style="width:100;height:100;background-color:#ff0000;"></div>

The above html displays a 100×100 red block. What do you think the effects of the html below?

<div style="padding: 20px; width: 100; height: 100; background-color: #ff0000;"></div>

Do you think the block now reserves 20px as the padding and shrinks to be an 80×80 red block? Unfortunately, this is not true. In fact, the red block now expands to 120*120.

The fact is the padding area is outside the area specified by width and height, and affected by the background color. The border of the block will include the padding area. So the html below will add a border right around the padding area.

<div style="padding: 20px; border: 1px solod; width: 100; height: 100; background-color: #ff0000;"></div>

The margin attribute further expands the block. It adds extra space outside the border.

<div style="margin: 20px; padding: 20px; border: 1px solod; width: 100; height: 100; background-color: #ff0000;"></div>

Now the block actually occupies 140*140 area, the outer area(the margin) is white space and the inner 120*120 area is a red block with a border.

The full notation of padding and margin property(the shorthand for margin-top,margin-right,margin-bottom, and margin-left property) is padding/margin:top,right,bottom,left. Note the padding/margin order is clockwise with top at first.

Leave a Reply