A problem I often have with CSS and forms is clearing elements that are floating. A lot of the time I will create a definition list to deal with form elements. If I then want them to all line up (radio buttons for example) I need to float the radio buttons and their lables to the left, and then apply clear left to the lables so each one is on a new line. The result is like so:

The problem with this is that the Definition list its self has no height, and anything after it won’t be able to see it’s floating content. The result is as follows:

This can be easily fixed by making anything directly following it a clear:left property. The problem with this is, it’s very hard to give the same margin below your element, apart from spercifically adding padding or margin to the element below.

In the past I have gotten arround this by adding in paragraph into the HTML with a clear:both property. This gives a solid element below all our floats that any following element can see, resulting in correct margins once again.

This is great but it means adding styling though HTML and meaningless content. Not great and useless if you change your design or are viewing in a browser that can’t use CSS.

The answer to this problem came to me through Position is everything’s: How To Clear Floats Without Structural Markup. By using the CSS 2 property: after: you can add content and then make that conent clear anything above it. Replacing my presentational HTML.

.dl:after {
    content: "."; 
    display: block; 
    height: 0; 
    clear: both; 
    visibility: hidden;

I changed the “full stop” to a space and it seems to work fine. There are also some little hacks to make it work in old IE too :)

This entry was posted on Tuesday, October 10th, 2006 at 11:23 am and is filed under CSS, Development. You can leave a comment and follow any responses to this entry through the RSS 2.0 feed.

Leave a Reply