The box model and margins

In the previous tutorials, we looked at the box model and how to add padding and borders to elements. In this tutorial, we will look at how to specify margins around boxes. Remember, padding is the transparent space around the content, borders go around the padding and content, and the margin is the transparent space around the outside of the border.

You can use CSS code to add a margin to any element on your webpage. For example, if you want some space around a heading of h1 size you could add the code margin: 2px; to the h1 selector in your CSS code to add two pixels of space around a h1 heading. You can also be more specific eg. margin-left: 2px; if you only wanted margin spacing on the left side of an element.

In the example image below, 50px of margin space has been added to the heading which has an orange background. The heading has a green border and is inside a div with a red border. The space between the green border of the heading and the red border of the div is the actual margin space (50px) around the heading. The space between the green border and the text inside the div is the margin space (20px). The green border is 5px thick and the red border is 2px thick.

Screen Shot 2017-04-14 at 4.20.08 pm

Watch the video below and then scroll down to see the sample code.

Check out the sample code below to add margins to your elements.

Here is the HTML code:

        <link rel="stylesheet" href="theme.css" type="text/css"/>

        <h1>This is a heading</h1>
        <h2>This is smaller heading</h2>
        <p>And this is a paragraph</p>

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

And here is the CSS code (the theme.css file):

    font-family: Arial;

    background-color: orange;
    padding: 20px;
    border: 1px solid red;
    margin: 50px;

    background-color: yellow;
    padding: 20px;
    border: 1px solid black;
    margin-left: 20px;
    margin-right: 20px;
    margin-top: 10px;
    margin-bottom: 5px;

    background-color: lightblue;
    padding: 20px;
    border: 1px solid black;
    margin: 10px 30px 10px 30px;

    margin: 10%;