This tutorial helps you learn how to adjust an element's padding area using CSS.
You can use the CSS padding properties to set the spacing between an element's content and its border (or the edge of the box of an element if it has no defined border).
The padding is affected by the background-color of an element. So, for example, if you set an element's background color, it will be visible through the padding area.
The paddings can be specified for an element's individual sides, such as the top, bottom, right, and left sides, using the CSS padding-top, padding-bottom, padding-right, and the padding-left properties, respectively. Let's take an example to see how it works:
Example :
h1 {
padding-top: 50px;
padding-bottom: 100px;
}
p {
padding-left: 75px;
padding-right: 75px;
}
You can specify the padding properties using the following values:
Note: The values for the padding properties cannot be negative.
The padding shorthand property is a property to avoid setting padding of each side separately, i.e., padding-top, padding-right, padding-bottom, and padding-left.
Consider the following example to see how it basically works:
Example :
h1 {
padding: 50px; /* apply to all four sides */
}
p {
padding: 25px 75px; /* vertical | horizontal */
}
div {
padding: 25px 50px 75px; /* top | horizontal | bottom */
}
pre {
padding: 25px 50px 75px 100px; /* top | right | bottom | left */
}
The padding shorthand notation takes one, two, three, or four whitespaces separated values.
Using the shorthand properties will help you save some time by avoiding the extra typing. In addition, it makes your CSS code easier to follow and maintain.
Adding padding or border to the elements while creating web page layouts can sometimes produce unexpected results because padding and border are added to the width and height of the box generated by the element.
For example, in case you set the width of an <div> element to 100% and you also apply left right padding or border on it, then a horizontal scrollbar will appear. Let's see an example:
div {
width: 100%;
padding: 25px;
}
You can use the CSS box-sizing property to prevent padding and border from changing the element's box width and height. In the example mentioned here, the width and height of the <div> box will remain unchanged. However, the content area of the element box will decrease with increasing padding or border.
Example ;
div {
width: 100%;
padding: 25px;
box-sizing: border-box;
}