On the web, we’re often presented with a list of values that we need to display in a comma-separated manner.
For example, perhaps I would rather display a list of city names like Amsterdam London Paris Berlin as:
Amsterdam, London, Paris, and Berlin.
While we could tackle this with a variety of approaches including PHP or Javascript, we can also easily handle it with CSS.
Here’s the HTML markup for the list of items:
<div> <span class="comma">Amsterdam</span> <span class="comma">London</span> <span class="comma">Paris</span> <span class="comma">Berlin</span> </div>
This CSS handles adding commas and the word ‘and’ on the last item:
.comma:not(:last-of-type):after { content: ","; } .comma:nth-last-of-type(2):before { content: none; } .comma:nth-last-of-type(2):after { content: " and "; }