CSS Padding Properties
Padding defines the space between the element's border and its content. CSS padding is specified just like margins — it can be set individually for each side, or all sides at once.
Set the Same Padding on all Sides
This example uses the padding
shorthand property to set the same padding on all sides of an element.
Setting Padding for Each Side
If you don't want the same padding settings to be applied to all four sides, or if you want each side to have different padding, you can use the following properties:
Example:
Shorthand Property
The padding
property is shorthand for padding-top
, padding-right
, padding-bottom
, and padding-left
.
Variations
Again, as with margin
, you don't need to provide different values for all four sides. You can provide one, two, three, or four values. Here's how it works:
If there is only one value, it applies to all sides. If there are two values, the top and bottom paddings are set to the first value and the right and left paddings are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.
In other words:
padding:10px;
- All four sides have padding of 10 pixels.
padding:10px 20px;
- Top and bottom have padding of 10 pixels.
- Right and left have padding of 20 pixels.
padding:10px 20px 30px;
- Top is 10px
- Left and right are 20px
- Bottom is 30px
padding:10px 20px 30px 40px;
- Top is 10px
- Right is 20px
- Bottom is 30px
- Left is 40px
Padding, Borders, and the Box Model
Applying padding (and borders) to an element can affect the size of that element. If you set an element to be 100 pixels wide, then apply padding of 10 pixels, the padding will increase the width to be 120 pixels.
This is because the default CSS box model adds padding and borders to the original box size. It looks at the specified width and height, then adds any borders and padding to that width and height.
This can be counter-intuitive and cause a lot of issues with trying to get layouts working right. It's especially confusing when working with percentages. For example, you set an element to a width of 100 percent but the border and/or padding pushes it out wider than 100 percent, effectively breaking your design.
This whole issue can be overcome by using the box-sizing
property. More specifically, using box-sizing: border-box
.
This keeps the box at the specified width/height, and draws the border and padding inside that specified height and width.
Many developers like to change the box model across all HTML elements and psuedo-elements. This can be helpful, as it keeps the box model consistent across all elements.
You can do this with the following code.