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.

Let’s summarize what the border,background, padding and margin are. The border surrounds the background area. The area outside the border and near the border is margin area. The margin extends till the adjacent element or the border of the parent. The area inside and close to the border is called padding area. The child elements inside the element are arranged in an area defined by width*height, which is surrounded by the padding area.

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. If you set both margin-left and margin-right, they may not be met at the same time, in this case, margin-left takes the precedence over margin-right. Similarly, margin-top takes the precedence over margin-bottom. The margin/padding can be a percentage, which means the percentage of the width of the parent element. So “margin-top:50%” means the top margin is 50% of the width(not height) of the parent. This is unlikeĀ  width/height. The percentage in width means the percentage of the width of parent while the percentage in height means the percentage of the height of parent.

Leave a Reply