Nested Elements and Margins

There are several differences between margins and padding. The most obvious is where you have a background or a border where the padding is included inside the border and shows the background while the margins are outside the border and don't show the background.

Another less obvious difference is that two adjacent elements with padding will have their padding applied separately. The margin between the two elements will not be the total of the two margins added together though, it will be the larger of the two meargin values only as the margins on separate elements are allowed to overlap one another (which is something that doesn't happen with padding).

Even less obvious is the way that margins work where one element is nested inside of another. Because margins are considered to be outside of elements and not a part of the element themselves the margins on an element that is itself contained within a second element need not be contained within that second element but can extend outside of it. The margins that apply to any given element are therefore not necessarily determined by the margin settings for that element itself but may be determined by the margins set on any element contained within that element which therefore may extend outside of it.

Let's consider an example. Let's say that we have a <div> with margins set to zero and the first thing within that div is a <p> with margins of five pixels. As a result of this the margin on the top edge of the pparagraph extends out beyond the margin on the top edge of the div with the result that the div is pushed down the page by that distance (note that this doesn't happen in Internet Explorer which doesn't process margins properly). If you have a background on your div you now have an unexpected gap between the top of that background and whatever is above the div on your page.

There are two ways to fix this. To fix it without changing the appearance of anything else on the page we need to make sure that the margins on all of the elements that could potentially extend out of the top of our div (or whatever othher edge is giving us the unexpected gap) are set to be no bigger than the margins set on the div itself. This will stop those margins from extending beyond where they are supposed to and will allow the div to be positioned where we want it to be.

The second way to fix this is to give the div a border. Where an element has a border of at least one pixel the margins of the elements contained within it are no longer able to extend beyond the element that contains them because they are constrained by that border. The margins on the inner element will now push that element in from the border rather than extending beyond that container as they do where no border is there.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate