CSS Guide Part 6 -Everything That You Need To Know About Margin And Padding

Posted by TotalDC

Margin and padding in CSS are the most used properties of spacing out elements. A margin is the space outside 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 set padding of 40px.

Those four sides of an elment can also be set individually – margin-top, margin-right, margin-bottom, margin-left and 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:

CSS box model

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: