Open boxes.html in your editor and save it as marginpadding.html.  Add a new paragraph containing a few words just under the div (but before the /body).

Margins and padding are both just areas of empty space.  Margins are outside the box and padding is inside.  There is already some space around and inside the div.  Save and view and notice how much.


In the style element at the top of marginpadding.html add a rule set with a type selector div.  In that rule set add this rule set:


Refresh the page in the browser and the div in should move slightly (down and right).  There is now an area of empty space around the border.  This margin will separate the div from anything else on the page (e.g. the new paragraph).  Try a bigger number if you are not sure.

You can set the margins individually using margin-left, margin-top, margin-right and margin-bottom.  You can set the margin and then change just one (e.g. margin-top) which you want different or you can change all of them.  Try this in marginpadding.html (you already have the first rule):

div {

Save and try.  Top and bottom margins will still be 50px but the others are changed.  The right margin will not look different in your current page as there is nothing to the right of it.


Add a new rule to the div rule set in the embedded styles to make the background colour green.  Save and view to test.

Padding is the same concept as margin but is space inside the border and around the text (or any other content).  Add this to the div rule set in the embedded style sheet:


Save and refresh the browser and you should see extra space around the text (between the text and border).  Note also that the div grew to allow this space for the padding.  This is the default behaviour and may not be what you expected (most people expect the available text area to shrink because the padding has taken up some of the space rather than the div to get bigger).  You will learn how to change this behaviour later.

You can also set padding-left and so on individually as you did with the margin.

The end resultThe page complete with margins and padding

You should now have something like this screen shot.  A nice box which could frame an image or some special text.

Note that in this screen shot the left margin (the bit between the edge of the browser and the left side of the box) looks to be more than 2px.  This is because the body element has padding.  This is added to the div margin to calculate the space between the edge of the page and the div.  All elements in HTML pages will have padding and margin unless you set them to 0.