2

i'm trying to use a CSS variable in a nth-child() selector, im using li:nth-child(3n+3) to give every third <li> a certain style.

this topic turned out to be very hard to google, i could not find any result for my use case.

currently my code looks roughly like this:

li {
  width: 25%;
  margin-right: 12.5%;
}
li:nth-child(3n+3) {
  margin-right: 0;
}

i want to refactor my code so it can be easily changed, but i can't figure out how to use CSS variables in the :nth-child(3n+3) selector. i want to achieve something like this:

:root {
  --number: 3;
}
li {
  width: calc(100% / (var(--number) + 1));
  margin-right: calc((100% / (var(--number) + 1)) / (var(--number) - 1));
}
li:nth-child(var(--number)n + var(--number)) {
  margin-right: 0;
}

sadly, the :nth-child(✖n + ✖) does not work as expected when using vars instead of numbers. my goal is to adjust the whole style with the one --number variable.

i created a codepen example: https://codepen.io/hergi/pen/xxRrmGv

any ideas/keywords or sources to help me solve this issue are highly appreciated, thanks in advance

SHRX
  • 559
  • 1
  • 6
  • 17

1 Answers1

-2

I think you want something like this..
You just need to use nth-of-type(3n+3)

You can't use Cascading variables in selectors.. for more detail visit this
Is it possible to use CSS vars in CSS3 selectors?

ul {
  display: flex;
  list-style: none;
}

li {
  width: 25%;
  margin-right: 12.5%;
}

li:nth-of-type(3n+3) {
  margin-right: 0;
}

li:nth-of-type(3n+3) button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  padding: 3px;
 }
<ul>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
  <li><button>Button</button></li>
</ul>
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
  • thanks for your answer, but that is not what i am trying to achieve, my goal is to be able to use a variable in my nth-selector instead of a fixed number. i was able to find a solution via JS, since these css nth-selectors dont seem to support variables – SHRX Feb 19 '21 at 05:43