Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Separating HTML list items by comma using CSS

4.89/5 (8 votes)
23 Feb 2012CPOL 46.9K  
Separating HTML list items by comma using CSS
Problem

In the HTML, we are displaying list of elements using the UL/LI structure. In some cases, we want to show a list of elements as an inline list separated by comma (,). We want to put list similar to the following structure:

HTML
<ul class="csv">
    <li>Serbia</li>
    <li>France</li>
    <li>UK</li>
    <li>Greece</li>
</ul>


In the programming languages, it is easy to create comma separated lists. After each item should be placed comma and the last comma at the end should be removed using some trim() function. However, in pure CSS, there is no trim function.

Solution

CSS code for creating comma separated lists is shown in the following code:

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


The first two lines put LI elements inline. The third line puts comma after each LI element. However, here is a problem because we will have one additional comma character at the end of the list, and we do not have trim() function.
Therefore, we are adding the fourth line that puts blank content after last LI element in the list.
This way you have true comma separated list implemented in pure CSS.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)