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. In the next tutorials, we will look at how to add margins and borders. 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.

Here is the HTML code:

<html>
    <head>
        <title>Box model</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
    </head>

    <body>
        <h1>This is a heading</h1>
        <h2>This is smaller heading</h2>
        <h3>This is an even smaller heading</h3>
        <p>And this is a paragraph</p>

        <img src="image.png" width="30%"/>
    </body>
</html>

And here is the CSS code (theme.css) with comments in the code:

body{
    font-family: Arial;
}

h1{
    background-color: yellow;
    padding: 20px; /* padding on all four sides */
}

h2{
    background-color: green;
    padding-top: 30px;
    padding-right: 20px;
    padding-bottom: 50px;
    padding-left: 30px;
}

h3{
    background-color: orange;
    padding: 10px 20px 10px 20px; /* top, right, bottom, left */
}

p{
    background-color: lightblue;
    padding: 10px 30px; /* top and bottom, right and left */
}

img{
    padding: 5%; /* you can also use % values */
}

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