The random eclecticisms of loonytoons

CSS firefox margins

I recently spent quite a while creating a template for a new site, so was not happy to find that sometimes a large chunk of white space would appear at the top, pushing down my background image and basically distorting the whole look of the page. And it only appeared to be happening in firefox!

Delving into it a little more, I realised it was in some way related to the borders that I would place around div elements during development so that I could easily see their exact positioning (I’m still not quite the CSS whizz, and this really helps me). When I thought I was finished with the layout I removed the borders and lo, the random white space appears!

Using a simplified example, the basic layout with the border round the main container can be seen here. The different background colours represent the different divs I’ve used.

Here’s the same page, but with that black border removed. Now there’s a large white space at the top of the page that seems unaccounted for in the source code, so if you imagine I bad it would look if I was using a background image that was then displaced.

From my research it seems that this has something to do with the behaviour of collapsing margins. The larger top margin that I have applied to the top_nav div is somehow also getting applied to the container div (being the parent div of top_nav), as the container div has no border and zero margin or padding (I don’t think it makes a difference that these zero values are directly set in the css).

Now I don’t claim to know exactly what is happening here as I’m no expert but it’s not a bug. Firefox is interpreting it correctly, it’s just different behaviour than we might expect. W3C talk about it, as do Complex Spiral Consulting, and in a forum reply Bill Brown also gives a very interesting graphical representation of the behaviour of margins.

For my specific problem, I solved it by adding “overflow: hidden;” to the css for my container div though quite why that works I don’t know. If someone could enlighten me further then please feel free, I am eager to know!


2 thoughts on “CSS firefox margins

  1. Jan says:

    Wow. I thought I was geeky for knowing how to program in HTML. Looks like you’re one step ahead of me!! 😛 I just can’t believe you’re doing this for a living now!! 🙂 By the way, very nice blog, I’m impressed!! 🙂 Think it’s about time I learnt some CSS! Hehe.

  2. loonytoons says:

    Geekiness is now indeed my trade :-). And really that post wasn’t great as I don’t have a full explanation for the behaviour but it’s a start!

Leave a Reply

Your email address will not be published. Required fields are marked *