How to add margins with CSS
Web Design with HTML & CSS
🕑 This lesson will take about 10 minutes
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.
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 and CSS code:
Next lesson: divs and spans