Previous Message
Next Message

Using clearing elements to prevent margin collapse

Sent by Michael Ryznar on 11 July 2004 01:01


I would like to add some vertical space between a 100% wide float and 
the next following div element. And so I added a margin-top to the 
following div element to create this vertical spacing. In experimenting 
with methods to achieve this spacing I have found an interesting 
characteristic with certain clearing elements. I only tested this in 
Mozilla 1.3.1 Mac os9 and so its difficult to draw any browser-wide 
conclusions.

Naturally, the top margin of the following div element slides under the 
preceeding floats - as it should - but I would like to prevent this in 
some situations.

And so I decided to use a clearing element to clear the float completely 
so that the margin-top property of the next following div would function.

Only certain clearing elements work however.

In terms of using a clearing element to prevent margin collapse 
surprisingly these common clearing techniques do not work:

<div class="clearer">&nbsp;</div>
<div class="clearer"><!-- --></div>
<div class="clearer"></div>
<br class="clearer" />

However these clearing elements do work:
<div class="clearer">b</div>
<div class="clearer">d</div>
<div class="clearer">g</div>

Very strange. Obviously there needs to be something substantial in the 
clearing element. But why do only certain characters work?

Here is my experiment [1]

Clearing elements work fairly well to contain floats (although it seems 
the perfect clearing element has yet to be found [2]), but unfortunately 
they don't seem to work very well to prevent collapsing margins - unless 
you actually put characters in them such as "b", "d" or "g" (or entire 
words.) It is not ideal (not semantic) to have to put full words into a 
clearing element and I would like to avoid this if possible.

Does anybody know how to make clearing elements behave better in 
preventing margin collapse? Maybe I am using clearing elements for the 
wrong purpose here and there is a better way to prevent margin collapse 
that doesn't require a clearing element.

[1] 
http://www.ryznardesign.com/web_coding/collapsing_margins/2004/preventing_margin_collapse.html
[2] http://www.pixelsurge.com/experiment/clearers.htm

Thanks for any comments,


--
Mike Ryznar



Ryznar Design
Burnaby, British Columbia
Canada

http://www.ryznardesign.com

______________________________________________________________________
css-discuss [EMAIL-REMOVED]]
http://www.css-discuss.org/mailman/listinfo/css-d
List wiki/FAQ -- http://css-discuss.incutio.com/
Supported by evolt.org -- http://www.evolt.org/help_support_evolt/
Previous Message
Next Message

Message thread:

Possibly related: