Margin and Padding In CSS

In the previous tutorial, the box model was discussed. The box model provides a layout of the margin and padding. In this tutorial, both will be discussed.

Padding in CSS

In the box model, the padding surrounded the content. The padding gives some space around this area based on what is specified.

The values for padding can be in pixels or even as a percentage.

p
{
padding: 20px;
}

Applying it as shown in the code snippet above sets the top, bottom, left and right padding to 20 pixels. Individual paddings can also be set as shown in the snippet below.

p
{
    padding-top: 20px; 
    padding-right: 30px; 
    padding-bottom: 25px;
    padding-left: 30px;
}

There is also a shorter way of setting all the padding in only one line.

p
{
padding: 20px 30px 25px 30px;
}

This method applies the same padding as in the snippet before. Using this method the padding is applied clockwise starting from top.

The first value represents the top padding, the second value represents the right padding, the third represents the bottom padding and the fourth, the left padding.

The Margin

In the box model, the margin is outside the border. It clears this area based on the CSS specifiation.

Just like the padding, the values can be specified in pixels or even as a percentage.

p
{
    margin: 10px;
}

As like padding, margins can also be defined individually.

p
{
    margin-top: 10px; 
    margin-right: 20px;
    margin-bottom: 15px;
    margin-left: 20px;
}

Margins can also be specified in one line in a clock wise fashion (top, right, bottom, left) as like padding.

p
{
    margin: 10px 20px 15px 20px;
}