Organizing lists in HTML/CSS
-
05-09-2019 - |
Question
I have a list and I need two sections in each item. I also need the first section to be of fixed width. How should I code it?
I've tried using definition lists:
<dl>
<dt style="width: 2em;">foo</dt><dd>bar</dd>
...
</dl>
... and user lists with span:
<ul>
<li><span style="width: 2em;">foo<span>bar</li>
...
</ul>
Neither worked. Are there any canonical ways to do that?
Solution
The way I came up with is, perhaps, not canonical (but only because I'm not convinced that there is a 'canonical' means of implementing it), but it does work:
<style type="text/css" media="screen">
#container
{width: 50%;
margin: 0 auto;
}
ol,
ul {border: 1px solid #ccc;
width: 90%;
padding: 1.4em 0;
}
ol li,
ul li {background-color: #ccc;
margin-left: 20%;
}
ol li span.list-head,
ul li span.list-head
{background-color: #ffa;
float: left;
display: block;
width: 6em;
}
dl {border: 1px solid #ccc;
line-height: 1.4em;
padding: 1.4em 0 0 0;
}
dl dt {background-color: #ffa;
display: block;
margin: 0;
width: 10%;
}
dl dd {background-color: #fc0;
display: block;
margin: 0;
width: 88%;
margin-left: 11%;
position: relative;
top: -1.4em;
}
</style>
...
<div id="container">
<ol>
<li><span class="list-head">Foo:</span> bar.</li>
<li><span class="list-head">Bar:</span> baz.</li>
<li><span class="list-head">Baz:</span> foo.</li>
</ol>
<ul>
<li><span class="list-head">Foo:</span> bar.</li>
<li><span class="list-head">Bar:</span> baz.</li>
<li><span class="list-head">Baz:</span> foo.</li>
</ul>
<dl>
<dt>Foo:</dt>
<dd>bar.</dd>
<dt>Bar:</dt>
<dd>baz.</dd>
<dt>Baz:</dt>
<dd>foo.</dd>
</dl>
</div>
There's a working demo over at: http://www.davidrhysthomas.co.uk/so/lists.html.
OTHER TIPS
Like Alan said but if you just put a div it won't work the way you want, try this:
<ul>
<li><div style="width: 200px; display: inline-block;">foo</div>bar</li>
<li><div style="width: 200px; display: inline-block;">foo12</div>bar</li>
<li><div style="width: 200px; display: inline-block;">foo12345</div>bar</li>
<li><div style="width: 200px; display: inline-block;">foo12345678</div>bar</li>
</ul>
(maybe you'd like to use a class instead of repeating the style attribute each list item)
Width does not apply to <span>
tags as they are inline. Try replacing the tag with a <div>
or <p>
or any other block element.
Use a dl and float the dt to the left.
<style type="text/css">
dt {clear:left; float:left; width: 8em;}
</style>
<dl>
<dt>foo<dt>
<dd>bar</dd>
<dt>foo1<dt>
<dd>bar1</dd>
<dt>foo12345<dt>
<dd>bar</dd>
</dl>
try either a label for the first portion or an inline div
I'd like to ask: is this for representing tabular data? We've been indoctrinated into thinking that HTML tables are evil, but for showing, well, a table of data, they're perfect. I've seen more than one coder try and duplicate the functionality of the <table>
tag using <div>
s and CSS.
Of course, if it's not, then please, carry on. :-)