Display HTML OL/UL list as comma-separated sentence with CSS

April 21st, 2010

On a site I’m currently working on, it seemed best to display an OL as a list in sentence form.

For example:

<ul class="commaList">
	<li>one</li>
	<li>two</li>
	<li>three</li>
	<li>four</li>
</ul>

Would display as: One, two, three and four.

In case this CSS is of any use to anyone else, I’ve published it as a snippet below.

Please note this uses pseudo-selectors and so will not work in IE, but will gracefully degrade.

/* display ordered list as comma list */
.commaList li:first-child {
	text-transform: capitalize;
}

.commaList li:after{
	content: ',';
	padding-right: 5px;
}

.commaList li:nth-last-child(2):after {
	content: '';
	padding-right: 5px;
}

.commaList li:last-child:before {
	content: 'and ';
	padding-right: 0;
}

.commaList li:last-child:after {
	content: '.';
	clear: both;
}

/* this prevents single item lists from containing commas and 'ands' */
.commaList li:only-of-type:before, .commaList li:only-of-type:after {
	content: '';
	padding: 0;
}

2 Responses to “Display HTML OL/UL list as comma-separated sentence with CSS”

  1. Phil says:

    Thanks for the tip, very useful. I have found myself writting this kind of specialist selector styling in an IE only jQuery file just to catch IE browsers which won’t render the CSS file properly. Not necesarily the cleanest way to do business, but it works across all browsers.

  2. Thanks! Exactly what i was looking for.
    Any ideas what to do with lists containing only one list element?

Add a comment