A few years back, when I was learning HTML and CSS, I found it difficult to differentiate between CSS margin and padding. In fact, at some point, I failed a quiz on these CSS properties. In the past two months, I have been taking the HTML/CSS microverse track. I have invested time, not only to understand but also to practice the CSS margin and padding properties.
If you are a beginner learning HTML and CSS, I don’t want you to struggle to understand these concepts. This is why I will explain them to you using simple analogies.
Imagine you have a piece of land and you want to build a house. First, you build a perimeter wall(defined border) around your land. When laying the foundation of your house(element), you are likely to leave some spacing between the perimeter wall and the house. If you build two houses(elements) in the same compound, you will have a spacing between the first house and the second house.
This spacing between the perimeter wall and the house, or from the first to the second house, should come into your mind when talking about margin.
According to w3schools, “The CSS margin properties are used to create space around elements, outside of any defined borders.”
You can set an element margin with the following properties:
example:
<div class="my-piece-of-land">
<div class="house1">My first house</div>
</div>
.my-piece-of-land {
width: 900px;
height: 300px;
background: grey;
}
.house1 {
width: 350px;
background: white;
margin: 100px; /* sets a margin of 100px from the defined boder from all direction */
margin-top: 10px; /* Specifies the top margin of an element */
margin-right: 10px; /* Specifies the right margin of an element */
margin-bottom: 10px; /* Specifies the bottom margin of an element.*/
margin-left: 20px; /* Specifies the left margin of an element.*/
}
After your house is complete, and you put a table(element’s content) inside the house. The space around the table from the house wall is what we will call padding.
According to w3schools, “The CSS padding properties are used to generate space around an element’s content, inside of any defined borders.”
You can set values for the padding on each side of the box using the following properties:
Example:
<div class="my-piece-of-land">
<div class="house2">My second house</div>
</div>
.house2 {
width: 350px;
background: magenta;
padding: 100px; /* Serves as shorthand for the preceding properties. */
padding-top: 10px; /* Specifies the top padding of an element */
padding-right: 10px; /* Specifies the right padding of an element */
padding-bottom: 10px; /* Specifies the bottom padding of an element.*/
padding-left: 20px; /* Specifies the left padding of an element.*/
}
Margin and padding are among the building block in HTML and CSS. These properties allow for the creation of an elegant layout in your design. You should spend time to deepen your understanding of these concepts. To dive deeper into these topics, check w3schools.com