What To Know About Margin And Padding In CSS
Posted by TotalDCMargin and padding in CSS are the most used properties of spacing out elements. A margin is the space outside the element and padding is the space inside the element.
For example, look at this code:
h2 {
font-size: 32px;
background-color: #lightgrey;
margin: 20px;
padding: 40px;
}
This leaves a 20-pixel width space around the secondary header and the header itself is 40px from all sides because there is a set padding of 40px.
Those four sides of an element can also be set individually – margin-top, margin-right, margin-bottom, margin-left, and the same with padding – padding-top, padding-right, padding-bottom, and padding-left. For beginners, this way should be much easier to understand.
The CSS Box Model
Margin, padding, and borders are known as The Box Model. The box model works like this: let’s say you have the content area which is in the middle, surrounding that there is padding and surrounding that – border and then surrounding that – margin. It looks just like this:
You don’t have to use all of these on the same element at once, but you have to remember that the box model can be applied to every element on the page.