News & UpdatesProgrammingWeb programming Store My Projects

CSS Tutorial – 17 – Margin and Padding

CSS tutorials

Margins, padding, and borders are all part of the so called box model of CSS. In this model the margin is the space around an element’s border and can be set using the margin properties.

margin (1-4) | margin-top | margin-right | 
margin-bottom | margin-left : 
  <length> | <percentage> | auto

Padding on the other hand is the space between the element and its border and is set using the padding properties. Neither the margin nor padding properties will inherit and they can be applied to all elements.

padding (1-4) | padding-top | padding-right | 
padding-bottom | padding-left : 
  <length> | <percentage>

A margin will appear around the border while padding will appear inside the border. Margin and padding can both use the percentage value, but only margin can have negative values. Padding is counted as part of the element’s background and will be affected by the background properties.

Just like the border properties, the margin and padding properties can be set with one to four values.

padding: 1 2 3 4; => top=1, right=2, bottom=3, left=4
padding: 1 2 3; => top=1, right=2, bottom=3, left=2
padding: 1 2; => top=1, right=2, bottom=1, left=2
padding: 1; => top=1, right=1, bottom=1, left=1

For example, in the declaration below the top/bottom margins will be 1 cm and the right/left margins will be 0.

margin: 1cm 0;

For both the margin and padding there are also separate properties for setting the individual sides.

margin-top:    1cm;
margin-right:  0;
margin-bottom: 1cm;
margin-left:   0;
Recommended additional reading:
Sams - Teach Yourself HTML and CSS in 24 Hours