What is the difference between padding and margins?

For those who would like to know more about HTML and CSS, today we will see about the difference between margin and padding CSS properties which allow us to add blank space between the HTML elements, preventing the elements from getting 'stuck' together.

Although both possess similar functions, each has its particularity. 
  1. Padding determines the inner margins, being responsible for determining the distance between the content of a given element and its border.
  2. Margin is applied to the outside of an element affecting how far the element is away from other elements.
For more info, please take a look at the picture below:

padding and margin, css proprieties
Difference between margin and padding

Just as you have the option to define the borders for each side of your HTML elements (eg. borders in 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​​.
These values ​​that you can select include: pixels (px), centimeters (cm), millimeters (mm). em units (em), x-height (ex), inches (in), picas (pc) and point sizes (pt).

By using margin and padding, you should add each value set in the four corners, as follows: top, right, bottom, left and each value must refer to 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.

Example 1: 

padding:5px 15px 5px 15px;
- top padding is 5px 
- right padding is 15px 
- bottom padding is 5px 
- left padding is 15px  

margin: 10px 5px 10px 5px;
- top margin is 10px
- right margin is 5px
- bottom margin is 10px
- left margin is 5px

If you define a single value, the distance applies to all sides, so it will be applied to the 4 sides of the HTML element that you want to modify.

Example 2:
padding: 5px (top and bottom) 15px (left and right);
margin: 10px (top and bottom) 5px (left and right);

If it helps to do it 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) and 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 the "space" after the border (outside the element = margin) or before the border (inside the element = padding).

0 comments:

Although every comment is appreciated, due to an overwhelming amount of questions, I can no longer provide personalized help. Keep in mind that comments are moderated and may take some time to appear. All spam comments will be deleted. Thanks for understanding!