Last Updated: March 08, 2016
·
14.58K
· anandhak

Displaying comma separated values using CSS

Often you have render lists (names, or other entities) in a complete English sentence.

For example, Bangalore Chennai Delhi Mumbai

as Bangalore , Chennai , Delhi and Mumbai

The first bit of CSS, adds the "comma" between HTML elements with the class attribute "comma", which is the easy part.

The second and third help putting the "and" instead of comma between the second last and the last element.

.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 ";
}

The HTML that it can style:

<div>
    <a href='#'>Bangalore</a>
    <aside class='comma'/>
    <a href='#'>Chennai</a>
    <aside class='comma'/>
    <a href='#'>Delhi</a>
    <aside class='comma'/>
    <a href='#'>Mumbai</a>
    <aside class='comma'/>
</div>
  • Note the use of the extra HTML tag "aside", this is just to keep the styling on the href, isolated from the "," separator.

  • The Tag could be aside or any other less commonly used HTML tag, just so that global CSS styling on a more common tag like <span> or <div> does not have side effects on the separator styling.

4 Responses
Add your response

Hi, if you use generated content - why not to use it in anchor element? and have clean markup.

over 1 year ago ·

This is the case were have these list generated in Rails (from erbs) or Javascript mustaches templates.

Instead of handling the exceptions around the adding the commas and the "and", it just seems sort of cleaner to do it declaratively in CSS. These separators just seemed like a view concern so leave it to CSS. (Maybe it is a little bit of an abuse of CSS, not sure about that).

over 1 year ago ·

This doesn't feel semantic at all, why not using <li>?

over 1 year ago ·

Very clever use of pseudo classes! There's a lot of potential there. i agree with the other commenters regarding semantics.

over 1 year ago ·