Make Marked-Up Lists Look Like Paragraph Text

Here’s a useful little snippet of CSS2 lifted straight off a personal project I’ve been working on. The following four rules display, find, and insert appropriate punctuation for making unordered lists read like English prose.

ul, ul li {
    display: inline; list-style: none; margin: 0; padding: 0;
}
li:after { content: ", "; }
li:last-child:after { content: "."; }
li+li:last-child:before { content: "and "; }

Here’s what’s happening.

  1. First they display the entire list and each list item as an inline element. This causes them to show up right up against any other text around them.
  2. Then they add a comma and a space after each list item.
  3. The last list item, however, gets a period and no space.
  4. Finally, the word “and” followed by a space is inserted before the last list item if, and only if, there is a list item before it (it has a sibling).

There you have it. List markup that looks just like a normal paragraph, complete with proper punctuation! A great little tip that makes lists a whole lot more flexible!

Note that as of this writing this won’t work in Internet Explorer because it can’t understand the last three rules. Since it does understand the first, the result will merely be an inline box for the whole list, sans punctuation.