CSS Padding

CSS

In this tutorial we will learn about CSS padding.

In the above image the area colored in green is the padding for the element highlighted in blue.

padding

It is the region between the border and content of the element.

We can set the value of padding in length, percentage and inherit. There is no auto value for padding.

We use px, mm, cm etc. to set padding in terms of length.

In the following code we have set the padding to 15px.

div {
	padding : 15px;
}

When padding is set to 0 then we don't use the px unit.

div {
	padding : 0;
}

To inherit the padding from the parent we use the inherit value for the padding property.

Padding value is not inherited from the parent element by default.

We cannot use negative value for padding.

Padding all 4 sides

To get better control we can set padding separately for each sides using the following properties.

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

In the following example we have set the padding of each sides of the div element having class container.

div.container {
	padding-top : 30px;
	padding-right : 15px;
	padding-bottom : 10px;
	padding-left : 5%;
}

padding shorthand

We can set the padding of each sides using the following shorthands.

div {
	padding : 30px 15px 10px 5%;
}

The above rule will set:

  • padding-top = 30px
  • padding-right = 15px
  • padding-bottom = 10px
  • padding-left = 5%
div {
	padding : 30px 15px 10px;
}

The above rule will set:

  • padding-top = 30px
  • padding-right = 15px
  • padding-bottom = 10px
  • padding-left = 15px
div {
	padding : 30px 15px;
}

The above rule will set:

  • padding-top = 30px
  • padding-right = 15px
  • padding-bottom = 30px
  • padding-left = 15px
div {
	padding : 30px;
}

The above rule will set:

  • padding-top = 30px
  • padding-right = 30px
  • padding-bottom = 30px
  • padding-left = 30px

Inherit padding

In the following example the child element is inheriting the padding from the parent element.

div.container {
	padding : 15px;
}

div.container p {
	padding : inherit;
}