Margins and Padding

Values can be set using the usual CSS units, e.g. px, em, ex, etc.


Specifying the values on their own, will give equal values to all four sides. e.g.:


p { margin: 5px;

border: 5px;

padding: 5px; }


Or to set individual values, use:

  • padding-top: 5px;
  • padding-right: 5px;
  • padding-bottom: 5px;
  • padding-left: 5px;
  • border-top: 5px;
  • border-right: 5px;
  • border-bottom: 5px;
  • border-left: 5px;
  • margin-top: 5px;
  • margin-right: 5px;
  • margin-bottom: 5px;
  • margin-left: 5px;


Shorthand examples:

  • 1 value sets all the same. margin: 1em ;
  • 2 pairs (top/bottom same, left/right same). margin: 1ex 0.5em ;
  • 3 values set in order: top, left/right pair, bottom. padding: 2ex 1em 4ex ;
  • 4 values Individually, in order TRBL. padding: 4ex 0.5em 5ex 3em ;



When an element has no borders, its margins and padding are adjacent, leaving them visually indistinguishable.


Also, Vertical margins collapse into a single gap. For example if two <p> elements both have their top and bottom margins set to 10px, there will only be 10px space between them, not 20px.




Negative margins can be used to offset or move/extend margin or padding or content outside it’s box container. This image depicts margins being set at -20px:


Leave a Reply