CSS padding

Padding in the CSS box modelPadding in the CSS box model

We've seen on the previous page how to draw a CSS border around an element. It's possible to control the space between the border and content by changing the so-called padding.

In fact, borders and paddings and part of the CSS box model. The picture on the right illustrates this concept. Every HTML element works this way.

Padding individual sides

You can change the padding of each element side separately by applying a length value to padding-top, padding-right, padding-bottom or padding-left.

CSS padding individual sides

h2, h3, h4, h5 {border:1px solid orange}
h2 {padding-top:2em}
h3 {padding-right:2em; text-align:right}
h4 {padding-bottom:2em}
h5 {padding-left:2em}
<h2>h2 with top padding</h2>
<h3>h3 with right padding</h3>
<h4>h4 with bottom padding</h4>
<h5>h5 with left padding</h5>

Output

Padding all sides

Similar to the border shorthand notations you can change all paddings through a single padding rule.

CSS padding

h2, h3, h4, h5 {border:1px solid orange}
h2 {padding:1em}
h3 {padding:1em 0; text-align:justify}
h4 {padding:1em 0 2em; text-align:justify}
h5 {padding:1em 2em 3em 4em; text-align:justify}
<h2>h2 uses 1em padding for all 4 sides</h2>
<h3>h3 has 1em padding for the top and bottom and 0 padding for the left and right side</h3>
<h4>h4 has 1em padding for the top, 0 for the left and right side and 2em for the bottom</h4>
<h5>h5 uses a different padding for each side going from top to right, bottom and left</h5>

Output