开发者

Styling DT to float left of DD

I'm trying to style a definition list such that each dt floats to the left of its corresponding dd elements. I have used:

dt {
    clear: both;
    float: left;
    width: 6em;
}
dd {
    margin-left: 6.5em;
}

which works as far as it goes. It nicely handles multiple dd elements per dt and dd text that is long enough to span multiple lines.

However, I'd really like to be able to cope with multiple dt elements per dd (which is valid HTML) and dt elements that are taller than the corresponding dd elements (due to length of text causing the lines to wrap). At this point the styling falls apart and subsequent dd elements get out of line with their dt.

I have tried various things such as floating the dd as well, which breaks alignment of multiple dd elements. Adding dd + dd { clear: 开发者_如何转开发both; } which almost works but now long dd text sits under its dt (not to mention older browsers not respecting the rule).

Has anyone managed to do this? I really don't want to give up and use a table but maybe it's appropriate.

My test markup is here: http://pastebin.com/nmAQ5Xdm


I have figured out a way to do this when you don't mind constraining the width of the dl element:

dl {
    max-width: 30em;
    overflow: hidden;
}
dt, dd {
    margin-top: 0.5em;
}
dt {
    clear: both;
    float: left;
    width: 6em;
}
dd {
    float: right;
    margin-left: 0.5em;
    width: 22.5em;
}

It's not perfect as the styling breaks if the viewport is too narrow for the dl.


This works for me. Set a width on the dt and float it left. Then leave the dd as display: block (default) and give it a margin-left of the same amount. Now the dd will wrap at the same width as the dt. The floating of your dt will clear the block dd automatically. You can adjust the spacing between the dt/dd pair by adjusting the margin-bottom of the dd.

If you might have empty dds, then you can add clear: both and margin-bottom to your dt too so that it will end up in the right place without dd content to put it there.

dt {
    float: left;
    width: 8em;
    clear: both;
    margin-bottom: 1em;
}
dd {
    margin-left: 8em;
}
dd {
    margin-bottom: 1em;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜