CSS padding properties are utilized to produce space around an element’s content, within any specified borders.
With CSS, complete control over padding is afforded. Properties exist for setting padding individually for each side of an element (top, right, bottom, and left).
CSS includes properties to specify padding for each side of an element:
These padding properties can be assigned the following values:
Note: Disallowing negative values.
Example
Assign varied padding to each of the four sides of a <div> element.
div { padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px; } |
To streamline the code, you can consolidate all padding properties into one using shorthand.
The padding property serves as a shorthand for the following individual padding properties:
Here’s how it operates:
When the padding property contains four values:
Example
Employ the padding shorthand property using four specified values.
div { padding: 25px 50px 75px 100px; } |
When the padding property contains three values:
Example
Utilize the padding shorthand property with three specified values.
div { padding: 25px 50px 75px; } |
Example
Apply the padding shorthand property using two specified values.
div { padding: 25px 50px; } |
When the padding property is set with a single value.
Example
Utilize the padding shorthand property using a single specified value:
div { padding: 25px; } |
The CSS width property defines the width of an element’s content area, which excludes padding, border, and margin (as per the box model).
Therefore, if an element’s width is specified, any padding applied to it will increase the total width of the element. This outcome is frequently considered undesirable.
Example
In this scenario, the <div> element is assigned a width of 300px. Nevertheless, the effective width of the <div> element will be 350px, comprising 300px width plus 25px of left padding and 25px of right padding.
div { width: 300px; padding: 25px; } |
To ensure that the width remains fixed at 300px regardless of the padding applied, you can utilize the box-sizing property. This property maintains the element’s intrinsic width, adjusting the available content space when padding is increased.
Example
Apply the box-sizing property to maintain a width of 300px, regardless of the padding amount.
div { width: 300px; padding: 25px; box-sizing: border-box; } |
Property |
Description |
padding |
A single declaration shorthand for defining all padding properties. |
padding-bottom |
Specifies the padding at the bottom of an element. |
padding-left |
Specifies the padding at the left of an element |
padding-right |
Specifies the padding at the right of an element. |
padding-top |
Specifies the padding at the top of an element |