Internal Server Error

what the voices in my head tell me to write

Tuesday, April 26, 2011

why did I never think of this 

Its a common problem. You have something like a definition list and you want to float the elements instead of displaying vertically down the page. That normally works fine for a 2 column layout where the dt is on the left and the dd on the right. Just add a "clear: left" to the dt. But what if you want to float all the elements so they just flow, and to make it extra hard the elements can be any width and the dt must always be next to the dd on the same "line".

JQuery to the rescue! first of all I created the following html structure

<dl class="content">
    <dt class="foo">Key</dt>
    <dd class="foo">Value</dt>
    <dt class="bar">Key</dt>
    <dt class="bar">Value</dt>

Next came the following JQuery

$('.content_context dt').each(function() {
     $(this).css('clear', 'none');
     dtOffset = $(this).offset();   
     ddOffset = $('dd.' + this.className).offset();
     if (ddOffset.top != dtOffset.top) {
        $(this).css('clear', 'left');

All this does is loop through the dt's in the list and check if their vertical offset is the same as the dd with the same classname. If its different (e.g. they are on different "lines" it adds a "clear: left" to the dt forcing it to be on the same "line" as the dd. Easy really.

Permanent link and Comments posted by Rob Cornelius @ Tuesday, April 26, 2011

Comments: Post a Comment

Links to this post:

Create a Link

links to this post
    follow me on Twitter

    My recent photos


    Creative Commons License
    This work is licensed under a Creative Commons License.

    RSS feeds and things

    Feed Button Help

    This page is powered by Blogger. Isn't yours?

    contact the author

    rob cornelius can be contacted by email use his name with an dot and googles web based email domain