Click here to Skip to main content
14,241,216 members

Separating HTML list items by comma using CSS

Rate this:
4.89 (8 votes)
Please Sign up or sign in to vote.
4.89 (8 votes)
23 Feb 2012CPOL
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:

<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:

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)

Share

About the Author

Jovan Popovic(MSFT)
Program Manager Microsoft
Serbia Serbia
Graduated from Faculty of Electrical Engineering, Department of Computer Techniques and Informatics, University of Belgrade, Serbia.
Currently working in Microsoft as Program Manager on SQL Server product.
Member of JQuery community - created few popular plugins (four popular JQuery DataTables add-ins and loadJSON template engine).
Interests: Web and databases, Software engineering process(estimation and standardization), mobile and business intelligence platforms.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1074221517-Apr-14 5:07
memberMember 1074221517-Apr-14 5:07 
GeneralReason for my vote of 5 Nice one! Pin
Ernesto Alejo Oltra29-Feb-12 9:10
memberErnesto Alejo Oltra29-Feb-12 9:10 
GeneralReason for my vote of 5 Nice one Pin
Nikhil_S24-Feb-12 18:24
professionalNikhil_S24-Feb-12 18:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Tip/Trick
Posted 21 Feb 2012

Tagged as

Stats

33.4K views
6 bookmarked