Although both have similar functions, each work in a different way.
- Padding determines the inner margins, being used for changing the distance between the content of a given element and its border.
- Margin is the space outside of an element affecting how far the element is away from other elements.
For a better understanding of how the padding and margin work, take a look at the picture below:
|Difference between margin and padding|
Just as you have the option to define the borders for each side of your HTML elements (eg. borders for the sidebar), you can do the same with the margin and padding properties. All you need to to do is to change the top, right, bottom and left values.
The values that you can use include: pixels (px), centimeters (cm), millimeters (mm). em units (em), x-height (ex), inches (in), picas (pc) and point sizes (pt).
When using margin and padding, you need to add a value for each 4 corners of an element, as follows: top, right, bottom, left. Each value must refer to the each side of the HTML element. The first value is for the top, and they follow a clockwise direction, so the value would be close to the right, then bottom, and finally, left.
padding:5px 15px 5px 15px;
- top padding is of 5px
- right padding is of 15px
- bottom padding is of 5px
- left padding is of 15px
margin: 10px 5px 10px 5px;
- top margin is of 10px
- right margin is of 5px
- bottom margin is of 10px
- left margin is of 5px
If you define a single value (instead of 4), the distance applies on the all sides, i.e. it will be applied on the 4 sides of the HTML element that you want to modify.
padding: 5px (top and bottom) 15px (left and right);
margin: 10px (top and bottom) 5px (left and right);
If it helps you visually, think of an A4 page of type inside a picture frame. The margin is the space between the edge of the sheet of paper and the other elements (the parts of the frame), while the padding would be the space between the edge of the sheet and where the type starts on the page. The border would be the edge of the sheet of paper.
It’s probably easier to understand if you have borders, then it also becomes obvious which one to use. Do you want “space” after the border (outside the element = margin) or before the border (inside the element = padding).