The box model and padding

Every element inside a web page can be considered as a ‘box’. In CSS, we use the term “box model” when we’re talking about the design and layout of HTML elements. The CSS box model is basically a box that is wrapped around each element. The box model consists of:

  • Content – the text and images
  • Padding – clear, transparent space around the content
  • Border – a border that goes around the padding and content
  • Margin – clear, transparent space around the border

When we use the box model, we can add padding, borders, and margins around the content in HTML elements such as headings and paragraphs. Every element inside your web page is actually a box. The image below shows the different parts of the box model.

The HTML box model
The HTML box model

The video below introduces the box model and shows how to add padding to boxes. Watch the video below and then scroll down the page to see how you can add padding to elements in your web pages.

The sample code below shows how to add padding. There are also some comments inside the /* and */ tags to help you remember the order of the widths for padding on each of the four sides of a box.

<!DOCTYPE html>
<html>
<head>
 <title>Box model and padding</title>
 <meta charset="utf-8"/>
 <style>
 h1{
 background-color:yellow;
 padding:20px;
 }
 
 h2{
 background-color:green;
 padding-top:50px;
 padding-right:20px;
 padding-bottom:50px;
 padding-left:20px;
 }
 
 h3{
 background-color:orange;
 padding:10px 20px 10px 20px; /*top right bottom left padding */
 }
 p{
 background-color:blue;
 padding:10px 30px; /* top and bottom, left and right*/
 }
 
 </style>
</head>
 
<body>
 <h1>This is a box.</h1>
 <h2>This is another box.</h2>
 <h3>This is a box too.</h3>
 <p>And yep, this is also a box.</p>
 
</body>
 
</html>

The next tutorials will show how to also add borders and margins to elements in your web pages.