Margins are empty space around an HTML element such as a paragraph or a DIV. They make a real difference to how a page looks.
The code you pasted in to boxmodel.html last time includes the simplest margin setting:
margin:10px;
Not too hard to work out. You get ten pixels of space around the DIV and its border.
You can set the margins individually. The right and bottom ones will only affect things if there are more objects to the right or the bottom or if the browser window is very small:
margin-top:100px;
margin-right:50px;
margin-bottom:100px;
margin-left:200px;
You can also use any other measurement (ems, pt etc.).
To centre a div on the page set it's width and set left and right margins to auto instead of using a set size.
Collapsing margins
Web standards say that if two block elements have top/bottom margins which touch (or which are nested inside each other) that the smaller margin will collapse. Picture two DIVs above each other. The top DIV has a margin of 20px and the lower one 15px. The gap between the borders of the DIVs will be 20px. Left and right margins are not affected and there are some fairly complex situations where the collapse should not happen.
<div style="margin-bottom:50px; background-color:red; height:50px;"></div>
<div style="margin-top:20px; background-color:blue; height:50px;"></div>
Try this. Change the margin size of the second DIV and there should be no change in layout. Until you set a margin of more than the margin of the first DIV. That probably seems sort of reasonable but this may not:
<div style="margin-top:50px; background-color:red; height:50px;">
<div style="margin-top:20px; background-color:blue; height:50px; width:400px;"></div>
</div>
The child DIV (the one inside the other one) will not have a margin when you try that code in a page. Now change the margin of the second element to 100px and both elements will be shown lower down the page. You probably expected the child to be separated from the parent by that margin but that is not what happens.
Don't worry too much about this just remember that margins sometimes collapse so that when your design won't work you can come back here to remind yourself why!




