Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma-delimited lists with CSS—I want an Oxford Comma!

Tags:

html

css

I'm attempting to extend an old CSS trick to new lengths, taking into account the sinister future of the Oxford Comma. I like the Oxford Comma. I want my inline lists to use it. That is,

I would like this html

<ul id="taglist">
  <li>apple</li>
  <li>orange</li>
  <li>banana</li>
</ul>

to show up as this:

apple, orange, & banana

Now, I can get it to show up as

apple, orange & banana

using this CSS:

#taglist {
  display: inline;
  list-style: none;
}

#taglist li {
  display: inline;
}

#taglist li:after {
  content: ", ";
}

#taglist li:last-child:after {
  content: "";
}

#taglist li:nth-last-child(2):after {
  content: " & ";
}

but the problem, you see, is that we can't simply change that last statement to content: ", & " because lists with only two items will look stupid. Like

I like to eat apples, & bananas

So for a list of 3 or more, I want a comma after the second-to-last element. For lists of two, I want no comma.

like image 811
chadoh Avatar asked Jul 05 '11 19:07

chadoh


2 Answers

I added this extra rule, it appears to do what you want:

#taglist li:nth-last-child(3) ~ li:nth-last-child(2):after {
  content: ", & ";
}
like image 182
Andrea Avatar answered Sep 17 '22 09:09

Andrea


I don't have enough reputation to leave comments yet, but I have something to share that I think is helpful.

I made a JSfiddle demo of chadoh's improved version of Taze T. Schnitzel's answer. I have also included and commented-out Taze's original answer and chadoh's first attempt at an answer. Here is the demo: http://jsfiddle.net/u7rzA/

like image 32
Rory O'Kane Avatar answered Sep 18 '22 09:09

Rory O'Kane