Skip to main content

Padding in the CSS Box Model (Live Playground)

Padding is an essential component of the CSS box model, creating space between the content and the border of an element. In this tutorial, you will learn about padding, how to set individual and shorthand padding properties, and how it affects the layout of elements, along with sample code and simple explanations.

Individual padding properties

You can set padding individually for each side of an element using the following properties:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

Example:

CSS
div {
background-color: lightblue;
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
}
HTML
<div>This div element has individual padding values for each side.</div>

In this example, the div element has 10px padding on the top and bottom and 20px padding on the left and right.

Live Playground, Try it Yourself

Shorthand padding property

The shorthand padding property allows you to set padding for all four sides in a single line of code:

  • padding: top right bottom left;
  • padding: top/bottom left/right;
  • padding: top left/right bottom;
  • padding: all;

Example:

CSS
div {
background-color: lightblue;
padding: 10px 20px;
}
HTML
<div>This div element has shorthand padding values for all sides.</div>

In this example, the div element has 10px padding on the top and bottom and 20px padding on the left and right using the shorthand padding property.

Live Playground, Try it Yourself

The effect of padding on layout

Padding affects the total size of an element and can influence the positioning of surrounding elements. It does not, however, affect the size of the content area.

Example:

CSS
.container {
display: flex;
}

.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin-right: 10px;
}

.box-padding {
padding: 20px;
}
HTML
<div class="container">
<div class="box">No padding</div>
<div class="box box-padding">With padding</div>
</div>

In this example, the div element with padding has a larger total size but retains the same content size as the div element without padding.

Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned about padding in the CSS box model and how to set individual and shorthand padding properties. By understanding the role of padding in the box model and how it affects the layout of elements, you can create more visually appealing and consistent designs across your web pages.