CSS Padding & Margin
By Tony 8.2.2024
To make a website visually pleasing and usable, the elements need to be simple and spaced out instead of small text and images all clumped together. With CSS's padding and margin properties, you can add space inside and outside different elements to make the website less dense, making it easier to take in and view the page.
padding: 50px;
margin: 50px;
If you think of an element as a box, then padding is the space between the content inside the box and the edge of the box. For example, you have a button where you want to add space between the text and the border of the button. You can give the button element a padding to create space on all four sides of the text. On the other hand, margin is the space outside of the element. It can seperate elements from each other by giving them a reserved space outside, which is the margin.
As you can see in the example above, the top element with a padding of 50px have much more space between the text and the edge of the blue box. That is padding at work, adding space inside the element. Conversely, the bottom element doesn't have any space inside of the blue box (no padding), but has much more blank space outside of the blue box. To have a better understanding of padding and margin, please play around with the values of the example above and see how the space changes.
padding-top: 50px;
margin-bottom: 50px;
Padding and margin adds space on all four sides of an element, but what if you only want to have padding on the top of an element? You'll want to use the property padding-top in this case. padding-top only adds space on the inside of the top of an element, and not the other three sides. There's also padding-left, padding-right, and padding-bottom, which are for the other 3 sides of the element. Margin works the same way too. But what if you only want to have padding on top and on the bottom of an element? You can use padding-block to achieve this. Use padding-inline to add spacing on the left and right of the inside of an element. There's a bunch of other padding and margin properties for direction control, so feel free to check out our references or search them up to master CSS padding and margin even more!
Padding and margin are similar, because they both add space to an element. The key difference is that padding adds space inside of the element, while margin adds space outside of the element. Also note that padding and margin won't work on HTML inline elements (img, a, span, etc), to make them work, set these elements to display: block; using CSS.