CSS Padding

The padding property creates space around element content.

Padding values are set using lengths or percentages. It cannot accept negative values. Its default value for all padding properties is 0.

Here are the CSS Padding Properties:

We can use padding property for all sides (top, bottom, left, right). For the top we use padding-top, for bottom padding-bottom, for left side padding-left and for right padding-right.

Let's see the examples.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        background-color: #1c87c9;
        color: white;
        padding: 20px 40px 20px 40px;
      }
    </style>
  </head>
  <body>
    <p>Paragraph with background-color, color and padding properties.</p>
  </body>
</html>

Now let's explain the code: we use background-color property for the background of our paragraph, color property for the color of our text, and finally we use padding property for the space around the element content. In this example the element content is our text which we have written in p element.

Now about padding: 20px 40px 20px 40px. This code means that the padding in the top side must be 20px, in the right side padding 40px, in the bottom side 20px and the left is 40px.

We use this property when we give values to all sides. It must look like this in code.

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

If all the sides have the same values (for example all sides are 50px) in css we can write it like this.

p {
  padding: 50px;
}

When we have the same values for the top and the bottom (for example 20px) and the same for the left and the right (for example 10px) we can write the following code.

p {
  padding: 20px 10px;
}

This is the same with the code above.

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

When the values for the left and the right are the same, for example 15px the top side is a 20px and the bottom is 35px, we will write the following code.

p {
  padding: 20px 15px 35px;
}

This is the same with the code above.

p {
  padding-top: 20px;
  padding-right: 15px;
  padding-bottom: 35px;
  padding-left: 15px;
}