In today’s tutorial we’re going to talk about how to use a super-popular CSS property: padding. You can think of the padding property as a way to add space within your elements — not to be confused with margins, which allow you to add space outside of your elements. Just like with margin though, you can add padding to the top, right, bottom, and left sides of an element. The padding property is actually shorthand for padding-top, padding-right, padding-bottom, and padding-left, in that order.
The padding property can take one, two, three, or four values. The values are usually in pixels, ems, or %, but you can actually use any unit of measurement you like. If you give the property one value, then that one value applies to all four sides of the element. So, for example, if you give your padding property a value of 10px, your element will have 10px of padding across the board.
If you give the property 2 values (say, 10px and 5px), then the first value will apply to the padding of the top and bottom sides of the element, while the second value will apply to the right and left sides of the element.
If you give the property 3 values (say, 10px, 5px, and 20px) then the first value will apply to the top side of the element, the second value will apply to the right and left sides of the element, and the third value will apply to the bottom side of the element.
Giving the padding property four values results means that each value will correspond to different sides of your HTML element. So if you have the value 10px 5px 20px 8px, then the first value is applied to the top, the second is applied to the right, the third is applied to the bottom, and the fourth is applied to the left. A good way to think about this sequence is to remember that each value is applied to different sides of the element starting at the top and moving clockwise.
Now, let’s see an example of the padding property in action. What follows is the image of a div with no padding applied to it:
After we add the following CSS code:
div{ padding: 10px 3px; }
We’ll end up with a div that looks like this:
As you can see, there’s now significantly more space between the border of the div and the content within the div, all thanks to padding.
Padding is a property that’s supported on every browser, so you should be able to use it pretty widely on your projects without having to worry about whether or not it’s going to be supported. Remember, the property doesn’t take negative values (unlike margin), so you can’t use it to play around with positioning much, but in terms of adding some extra space to your elements, there’s nothing better to use than the padding property. Play around with it to be sure that you’re comfortable using it, because it’s one that will surely come up a lot in your coding adventures.