CSS PADDING
Padding property in CSS is used to create space inside of any defined borders or around an element’s content. With this we have full control over the padding. There are properties that set the padding for each element i.e. padding-top
, padding-right
, padding-bottom
, and padding-left
.
There are two ways in which we can define the mentioned properties:
- Declaring individual sides.
- shorthand.
The values are given to these properties in terms of px
(pixels), cm
, pt
, %
of the width of the containing element, etc. Negative values are not allowed in them.
Declaring individual sides
Paddings for all the four sides can also be defined indiviually.
For example:
div {
padding-top: 20px;
padding-right: 10px;
padding-bottom: 20px;
padding-left: 10px;
}
Live Demo!
Padding - Shorthand Property
It is possible to specify all the padding properties in one line. This shortens the code and makes it cleaner.
For example:
padding: 20px 10px 20px 10px; /* padding: top right bottom left */
Live Demo!
If the padding property has four values, then:
-
top padding is 25px.
-
right padding is 50px.
-
bottom padding is 75px.
-
left padding is 100px.
If the padding property has three values:
padding: 25px 50px 75px;
Live Demo!
-
top padding is 25px.
-
right and left paddings are 50px.
-
bottom padding is 75px.
If the padding property has two values:
padding: 25px 50px;
Live Demo!
- top and bottom paddings are 25px.
-
right and left paddings are 50px.
If the padding property has one value:
padding: 25px;
Live Demo!
- All four paddings are 25px.
Let's check an example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
padding: 15px 30px 45px 60px;
background-color: lightblue;
}
</style>
</head>
<body>
<div> The padding shorthand property with top padding of 15px, right padding of 30px,
bottom padding of 45px & left padding of 60px.</div>
</body>
</html>
Live Demo!
Output
Padding and Element Width
This property specifies the width of the element's content area. The portion inside the padding, border, and margin of an element is the content area.
So, the padding added to that element will be added to the total width of the element even if an element has a specified width,. This often results in confusing outputs.
For example:
div {
width: 100px;
padding: 10px;
}
Live Demo!
Here, the <div>
element is given a width of 100px. However, the actual width of the <div>
element will be 120px (100px + 10px of left padding + 10px of right padding).
To keep the width at 100px, no matter the amount of padding, the box-sizing property is used, causing the element to maintain its width; if the padding is increased, the available content space gets decreased.
For example:
div {
width: 100px;
padding: 10px;
box-sizing: border-box;
}
Live Demo!
So in this way, the width can be kept 100px, irrespective of the padding!