Inline defintion lists

I’m a big fan of semantic HTML. When content describes a list of things, a developer should use a <ul>. Even if you don’t want it to be a bulleted list, or maybe want the elements to all be on a single line, use the appropriate semantic tags — search engines and screen readers will appreciate the improved readability.

So what if you don’t want a list to look like a list? CSS has long since progressed to the point where it’s possible to display HTML elements any way we like. 

Which brings me to one of my favorite recent tricks: inline <dt> and <dd> elements (“defintion title” and “definition data” inside a <dl> “definition list”).

Normally, a <dl><dt><dd></dl> combination looks something like this:

dt
    dd
    dd
dt
    dd
    dd

But there are times when you want to make it more compact, like this:

dt dd dd
dt dd dd

Enter the power of display:inline — with a few extra tricks. We also need to remove the margins on the <dd> so that it’s not indented. Simple enough:

dl.inline dt,
dl.inline dd {
    display: inline;
    margin: 0;
}

Next, we need to force each <dt> onto a new line. We can do this with :before CSS generated content — insert an \A (newline character) and add white-space:pre to make sure it’s rendered as such:

dl.inline dt:before { /* forces a new line */
    white-space: pre;
    content: "\A"; /* newline character */
}
dl.inline dt:first-child:before { /* first line */
    content: "";
}

Add a few more styles for presentation purposes, and we’re ready to go. The end result is a little complicated, but much more readable and compact when rendered in the browser:

dl.inline dt,
dl.inline dd {
    display: inline;
    margin: 0;
}
dl.inline dt {
    font-weight: bold;
}
dl.inline dd:before {
    content: " ";
}
dl.inline dt:before { /* forces a new line */
    white-space: pre;
    content: "\A"; /* newline character */
    font-size: 130%; /* a little extra spacing */
    vertical-align: top;
}
dl.inline dt:first-child:before { /* first line */
    content: "";
    font-size: 100%;
}

http://jsfiddle.net/mblase75/q2SGS/

Leave a Reply

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

*