Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use child index in calc in CSS?

Tags:

html

css

css-calc

What I'm looking to achieve is each child having a diffrent color than the previous one (result would be gradient-like) by multiplying the color value with the child index.

Pseudo-code:

.parent > div:nth-child() {
    background-color: rgb(index * 10, 255, 255);
}
like image 211
lumetorm Avatar asked Oct 18 '25 11:10

lumetorm


1 Answers

As one of the solutions, you can assign values directly from JavaScript. But if you really want to manage this through CSS, then you can force the elements to set indexes using JS and CSS Variables and using calc() the necessary calculations in CSS rules. Example below:

document.querySelectorAll('.parent > div').forEach((el, index) => el.style.setProperty('--custom-index', index));
.parent > div {
  height: 50px;
  width: calc(30px + 50px * (var(--custom-index) * 0.5));
  margin-top: 5px;
  background-color: rgb(calc(var(--custom-index) * 10), calc(var(--custom-index) * 40), calc(var(--custom-index) * 50));
}
<div class="parent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

But if you delete or add elements, then in this case you will need to re-run the script provided in the JS example to recalculate.

like image 110
Oleg Barabanov Avatar answered Oct 20 '25 02:10

Oleg Barabanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!