Samthedevman's Blog

What is the difference between Margin, Border, and Padding?

Lets first learn what they are. Margin, border and padding are styling tools to manipulate the style of an element using CSS. An element is a piece of code within HTML, with HTML being the structure of every website. Have a look at the image below, this is called the box model.

The margin represents the space surrounding the element outside of the border (in this example, content represents the element we are styling). Borders are borders around an element, in this example it is a green border. The padding represents the space inbetween the border and the element we are styling. At first the difference between margin and padding can be confusing, especially when there is no border. They are both used to make spaces between things like the border and other elements. Margin, padding and borders can be added to all four sides of an element or just one, the power is in the developers hands. Lets run through some examples.

Here are two pictures of the same nft above, they are both 1 element each. They are spaced apart from each other using margin. The margin in this example is 1vw (vw stands for viewport width, 1vw = 1% of a screens width, vw margins help keep websites responsive, no matter what device someone may be viewing this site on). Lets see what it would look like if we tripled this margin.

As you can tell above its a much bigger gap between the images. Lets look at the code.

This snapshot of code was taken from the css file that styles this page. The top block of code represents the 1vw margin applied to the left and right of the image and the bottom block of code represents the vw margin after it has been tripled. So you may be thinking the gap between the first two images is 1vw but its actually 2vw this is because we have applied margin to the left and right of each image(element), with the latter example images(elements) gap being 6vw.

Alright lets look at an example of padding. I have added red borders to the images below just to make it a bit easier to see the difference.

The image(element) above on the right has had a padding of 1vw applied to all four sides. The image(element) is still the same size, but now with padding, its pushed the boarders 1vw out on each side. Lets look at the code for both the css and html this time.

Look at the css in the example image above. In the top block of code, we can see it has the border applied to it, the border being 1px solid red. The block of code on the bottom represents the padding being applied to the right image(element) from the previous example. Now lets look at the html code. We are using the html to our advantage here to only style the right image with padding. This is done so using the class name .htmlCssPaddingExample.

We could go more indepth about class names and html structure, but this post is just about sheding some light on the difference between margin, border and padding.