13

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.

3
  • 1
    did you try your code with two elements? It is working Jul 5, 2011 at 19:31
  • 1
    It works, but it doesn't have the Oxford comma.
    – mystery
    Jul 5, 2011 at 19:58
  • 2
    +1 for the Oxford comma
    – erroric
    May 15, 2014 at 20:08

2 Answers 2

16

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: ", & ";
}
1
  • 5
    Perfect! I didn't know about the General Sibling Combinator! This can also be accomplished with the Adjacent Sibling Combinator with less characters, using #taglist li:nth-last-child(3) + li:after.
    – chadoh
    Jul 7, 2011 at 13:32
4

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/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.