Padding defines the space between the element's border and its content. CSS padding is specified just like margins - they can be set individually for each side, or all sides at once.
Setting Padding on all Sides
This example uses the
padding
property to set padding on all sides of an element.
<p style="border:1px solid orange;padding:20px;">
This text has padding of 20 pixels on all four sides.
</p>
This results in:
This text has padding of 20 pixels on all four sides.
Setting Padding for Each Side
If you don't want the 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:
<p style="border:1px solid orange;padding-left:60px;">This text has left padding of 60 pixels.</p>
This results in:
This text has left padding of 60 pixels.
Shorthand Property
Along similar lines to the
margin
shorthand property, the
padding
property is shorthand for
padding-top
,
padding-right
,
padding-bottom
, and
padding-left
.
Code:
<p>With padding:</p>
<div style="border:1px solid orange;width:100px;padding:20px 10px 0px 100px;">
Padded div
</div>
<p>Without padding:</p>
<div style="border:1px solid orange;width:100px;">
Non-padded div
</div>
Result:
With padding:
Padded div
Without padding:
Non-padded div
As you can see, applying padding to an element can affect the size of that element. In the example above, both
<div>
elements are specified to be 100 pixels wide. However, the padding on the first
<div>
pushes the size out, resulting in a larger
<div>
.
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