如何在 CSS 中将无序列表样式设置为逗号分隔的文本

我正在寻找一种方法,用 CSS 在 XHTML 中设计一个无序列表的样式,这样它就可以内联呈现,列表项用逗号分隔。

例如,下面的列表应该呈现为 apple, orange, banana(注意列表末尾缺少逗号)。

<ul id="taglist">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>

目前,我使用下面的 CSS 来设计这个列表的样式,它几乎可以完成我想要的任务,但是将列表呈现为 apple, orange, banana,(注意香蕉后面的逗号)。

#taglist {
display: inline;
list-style: none;
}


#taglist li {
display: inline;
}


#taglist li:after {
content: ", ";
}

有没有办法用纯 CSS 来解决这个问题?

37041 次浏览

To remove the trailing comma, use the :last-child pseudo-class, like so:

#taglist li:last-child:after {
content: "";
}

It depends on browser implementation, but this should work. Though it relies on first-child, which may limit its use, but essentially puts the comma-space ", " before the list-item, rather than after. I'm not sure how padding/margins will affect this, but if you use `display: inline; with margins and padding set to zero, it should be okay.

#taglist li:before {content: ", ";}
#taglist first-child {content: ""; } /* empty string */

Edited: to respond to corrections offered in comments by Jakob.

The following works (demo page here: http://davidrhysthomas.co.uk/so/liststyles.html:

#taglist    {width: 50%;
margin: 1em auto;
padding: 0;
}


li      {display: inline;
margin: 0;
padding: 0;
}


li:before   {content: ", ";
}


#taglist li:first-child:before
{content: "";
}

Although the commas are strangely floating-in-the-middle-of-nowhere, and, honestly, I prefer the accepted answer anyway. But just so's I wasn't leaving a horribly broken answer lying around, I thought I should fix it.

Thanks, Jakob.

There is no pure css way to do it that's cross-browser compatible ( thanks to Microsoft ). I suggest you just do it with server-side logic.

You can probably get close with using a last class on the last li and using background images for all lis but the last, but you will not be able to do :last-child and content: in IEs.

This is the way that the guys at A List Apart recommend in their article “Taming Lists":

#taglist ul li:after {
content: ",";
}


#taglist ul li.last:after {
content: "";
}

This requires having the last item in your list tagged with a class attribute value of “last”:

<ul id="taglist">
<li>apple</li>
<li>orange</li>
<li class="last">banana</li>
</ul>

Replace one your rule

#taglist li:after {
content: ", ";
}

with just another one

#taglist li + li:before {
content: ", ";
}

Pros:

  • One rule do all the work.
  • No rules for cancel previous rule,
  • IE8 Support

It's easy with CSS3 you can use pseudo selector last-child and not at once:

ul#taglist li:not(:last-child):after {
content: ", ";
}

Check results here https://jsfiddle.net/vpd4bnq1/