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.

<!DOCTYPE html>
<html>
<head>
 <title>Box model and margins</title>
 <meta charset="utf-8"/>
 <style>
 body{
 margin: 0px;
 border: 2px red solid;
 }
 h1{
 background-color:orange;
 padding:20px;
 border-style:solid;
 border-width:5px;
 border-color:green;
 margin:50px;
 }
 h2{
 background-color:yellow;
 padding:20px;
 border: 3px dashed blue;
 margin-left:20px;
 margin-right:20px;
 margin-top:10px;
 margin-bottom:10px;
 }
 p{
 background-color:blue;
 padding:20px;
 border-top: 8px dotted red;
 border-left: 8px dashed yellow;
 border-right: 8px solid green;
 border-bottom: 8px groove black;
 margin:10px 30px 10px 30px; /*top right bottom left*/
 }
 </style>
</head>
 
<body>
 <h1>This is a box</h1>
 <h2>This is another box</h2>
 <p>And another box</p>
 
</body>
 
</html>