HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

CSS Padding

CSS padding is a property that defines the space between an element's content and its inner border. It is used to create space inside the boundaries of an element. The padding can be applied to all four sides of an element (top, right, bottom, left), or you can specify individual values for each side.

This element has a padding of 70px.

Padding - Shorthand Property

The shorthand property for setting padding in CSS is simply called padding. It allows you to set the padding for all four sides of an element in a concise way. The general syntax is:

Example

div {
  padding: top right bottom left;
}
You can click on above box to edit the code and run again.

Output

Here are some examples:

Example

div {
  padding: 10px; /* Applies 10 pixels of padding to all sides */
}
You can click on above box to edit the code and run again.

Output

Example

div {
  padding: 10px 20px; /* 10 pixels on top and bottom, 20 pixels on right and left */
}

Example

div {
  padding: 10px 20px 30px 40px; /* 10 pixels on top, 20 pixels on right, 30 pixels on bottom, 40 pixels on left */
}
You can click on above box to edit the code and run again.

Output

Using the padding shorthand property can make your CSS more concise, especially when you need to set the same value for all sides or specific values for different sides. Just remember that the values are applied in the order of top, right, bottom, and left. If you provide fewer than four values, they are applied in a clockwise manner, starting from the top.

Padding and Element Width

The CSS width property specifies the width of the element's content area. The content area is the portion inside the padding, border, and margin of an element (the box model).

So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.

Example

div {
  width: 300px;
  padding: 25px;
}
You can click on above box to edit the code and run again.

Output

This div is 300px wide.

The width of this div is 350px, even though it is defined as 300px in the CSS.

To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.

Example

div {
  width: 300px;
  padding: 25px;
  box-sizing: border-box;
}

You can click on above box to edit the code and run again.

Output

This div is 300px wide.

The width of this div remains at 300px, in spite of the 50px of total left and right padding, because of the box-sizing: border-box property.