< img src=" https://websitedesign-usa.com/wp-content/uploads/2021/01/how-to-include-commas-in-between-a-list-of-products-dynamically-with-css.jpg" class=" ff-og-image-inserted "> Picture you have a list of products. State, fruit: Banana, Apple, Orange, Pear,
Nectarine We might put those commas (, )in the HTML, however let’s take a look at how we might do that in CSS rather, offering us an additional level of control. We’ll make certain that last product does not have a comma while we’re at it.
One option I discovered rather classy option is utilizing basic brother or sister combinator. We’ll get to that in a minute. Let’s begin with some example HTML. State you start with a list of fruits:
<< pre rel=" HTML">
>< ul class=" fruits <" >< li class>=" fruit on" > Banana << li class=">fruit on" > Apple< li >< li class=">fruit on" >
< li class =" fruit on "> Pear
< li class =" fruit on" > Nectarine. And some standard CSS to make them appear in a list:< pre rel= "CSS" class=" wp-block-csstricks-code-block language-css "data-line >. fruits. fruit .. fruit.on display screen: inline-block; Now state things take place inside this user interface, like a user toggles controls that filter out all fruits that grow in cold environments. Now a various set of fruits is revealed, so the
fruit.onclass is controlled with the
Far, our HTML and CSS would produce a list like this:
< pre rel class=" wp-block-csstricks-code-block language-none" data-line > BananaOrangeNectarine Now we can grab that basic brother or sister combinator to use a comma-and-space in between any 2
< pre rel=" CSS" class=" wp-block-csstricks-code-block language-css" data-line >. fruit.on ~. fruit.on:: prior to code>< Good! You may be believing: why not simply use commas to all the list products and eliminate it from the last with something like
: last-of-type. The problem with that is the last kid may be "off" at any provided time. What we actually desire is the last product that is "on," which isn't quickly possible in CSS, considering that there is absolutely nothing like "last of class" readily available. The basic brother or sister combinator technique!
In the UI, I utilized
display screenand toggled that in between
0and an affordable optimum worth so that I might utilize shifts to press products on and off more naturally, making it much easier for the user to see which products are being included or eliminated from the list. You can include the very same result to the pseudo-element too to make it incredibly smooth.
Here's a demonstration with a number of examples that are both small variations. The fruits example utilizes a
concealedclass rather of
on, and the veggies example has the animations. SCSS is likewise utilized here for the nesting:
I hope this assists others trying to find something comparable!