When a list is rendered as a set of sibling elements, the separators between items can live in CSS rather than in the markup. Keeping them out of the HTML matters most when items are toggled at runtime: if JavaScript hides or reveals entries with the classList API, hard-coded commas go stale, while selector-driven ones follow the DOM. Starting from a list of fruits — Banana, Apple, Orange, Pear, Nectarine — here is how to let CSS supply the comma and space between visible items without a trailing punctuation mark.
The markup and baseline styles
A fruit class marks each item, and the basic CSS makes the elements lay out as a list:
<ul class="fruits">
<li class="fruit on">Banana</li>
<li class="fruit on">Apple</li>
<li class="fruit on">Orange</li>
<li class="fruit on">Pear</li>
<li class="fruit on">Nectarine</li>
</ul>
.fruits {
display: flex;
padding-inline-start: 0;
list-style: none;
}
.fruit {
display: none; /* hidden by default */
}
.fruit.on { /* JavaScript-added class to reveal list items */
display: inline-block;
}
Why :last-child falls short
Applying a comma to every item and stripping it from :last-child or :last-of-type looks simpler, but the last child in the markup may itself be hidden at any given moment. What the layout needs is the last item that is currently shown — a "last of class" selector, which CSS does not provide. That gap is what makes the sibling-combinator approach necessary.
Separating with the general sibling combinator
Visibility is tracked with an on class, so as filters change which fruits remain in view, the rendered list becomes something like:
BananaOrangeNectarine
The general sibling combinator selects any on element that follows another on element, so the separator is attached only where one visible item is preceded by another. The item at the start of the run gets no separator, and neither does a single visible item:
.fruit.on ~ .fruit.on::before {
content: ', ';
}
Hiding with max-width for smoother transitions
To improve the transition, the original implementation swapped display for max-width and toggled it between 0 and a sensible maximum, so items can be animated on and off and users can see what is being added or removed. The same effect can be applied to the pseudo-element that draws the separator for a smoother result.
A demo contains two variations: a fruits example using a hidden class in place of on, and a veggies example with the animations. Both use SCSS for nesting.




