Padding is used to create space around an element’s content, inside of any defined borders. Here, you will get to know & understand completely about the CSS Padding along with syntax and example codes.
- CSS Padding Property
- Define Paddings for Individual Sides
- CSS Padding Example
- Padding – Shorthand Property
- Using the padding shorthand
CSS Padding Property
The padding CSS property is usually used in CSS to add space in the inner side of an element.
Syntax:
/* Apply to all four sides */ padding: 1em; /* vertical | horizontal */ padding: 5% 10%; /* top | horizontal | bottom */ padding: 1em 2em 2em; /* top | right | bottom | left */ padding: 5px 1em 0 2em; /* Global values */ padding: inherit; padding: initial; padding: unset;
Also Refer:
Define Paddings for Individual Sides
CSS has properties for specifying the padding for each side of an element:
padding-top
padding-right
padding-bottom
padding-left
Property | Description |
---|---|
padding | It is used to set all the padding properties in one declaration. |
padding-left | It is used to set the left padding of an element. |
padding-right | It is used to set the right padding of an element. |
padding-top | It is used to set Top padding of an element. |
padding-bottom | It is used to set the bottom padding of an element. |
All the padding properties can have the following values:
- length – specifies padding in px, pt, cm, etc.
- % – specifies padding in % of the width of the containing element
- inherit – specifies that the padding should be inherited from the parent element
Note: Negative values are not allowed.
CSS Padding Example
<!DOCTYPE html> <html> <head> <style> div { padding: 50px; border: 1px solid #black; } </style> </head> <body> <h2>CSS Padding</h2> <div>This element has a padding of 70px.</div> </body> </html>
Output:
Padding – Shorthand Property
In order to shorten the code, it is feasible to define all the padding properties in one property.
The padding
property is a shorthand property for the subsequent individual padding properties:
padding-top
padding-right
padding-bottom
padding-left
So, here is how it works:
If the padding property has four values:
padding: 100px 70px 50px 25px;
- top padding is 100px
- right padding is 75px
- bottom padding is 50px
- left padding is 25px
Using the padding shorthand
The usage of those is very simple and cannot be confused, for example:
1 value
Utilizing a single value implements that to all the paddings: top, right, bottom, left.
padding: 20px;
2 values
Working 2 values utilizes the first to bottom & top, and the second to left & right.
padding: 20px 10px;
3 values
Using 3 values practices the first to top, the second to left & right, the third to bottom.
padding: 20px 10px 30px;
4 values
Using 4 values applies the first to top, the second to the right, the third to bottom, the fourth to left.
padding: 20px 10px 5px 0px;