Home > Blockchain >  CSS Pseudo Elements - Target Several Elements in a Single Parentheses Pair
CSS Pseudo Elements - Target Several Elements in a Single Parentheses Pair

Time:12-31

I have an unordered list with several list points in an HTML. In my CSS, I want to target the 5th and 7th list points. So I go

.my-list li:nth-child(5, 7){
background:yellow;
}

Nothing. It only works with a single number. So I assume I cannot separate them with a comma. What character/symbol should I separate them with? Is this even possible? Alternative solution? I doubt that I need to rewrite a target for every single nth element in my list... We're nearly in 2022. Just my reasoning.

CodePudding user response:

Given your specific example, it’s somewhat easier to select the 5th and 7the elements than “[rewriting the] the [selector] for every single nth element,” using :is():

.my-list li:is(:nth-child(5),:nth-child(7)) {
  background:yellow;
}

But it remains a somewhat verbose alternative, in contrast to the approach you desire, which is, as yet, not possible.

If JavaScript was an option, then a simple utility function could retrieve the desired elements, but not in CSS alone as yet.

CodePudding user response:

There is no symbol for that. You can separate them like this:

.my-list li:nth-child(5),
.my-list li:nth-child(7) {
    background: yellow;
}

If you use css-preprocessors you can write it a little bit cleaner, especially if you'll give class for list item:

.item {
    &:nth-child(5),
    &:nth-child(7) {
        background-color: #fff;
    }
}
  • Related