SomoKRoceS
SomoKRoceS

Reputation: 3043

Style an element using the order of its class name appearance in the DOM hierarchy using css only

I was wondering if it is possible, using css only, to set a value of an element property using its rendering order in DOM within the same class name.

Example for making the question more clear:

Assuming I have a class named demo and I am willing to render two elements with demo as their class:

<div id="first" class="demo"></div>
<div id="second" class="demo"></div>

Now, in my .css file demo is defined:

.demo{
    font-size: 10px
}

What I want to achieve is that the div with the id first will have font-size of 10px and the div with the id second will have font-size of 20px. And every other div that is dynamically rendered afterwards with the same class name demo, will have font-size of calc(10*appearnceNumber)+'px'. (id=first div is the first element of class demo so appearnceNumber will be 1 and the font-size will be 10px).

Upvotes: 0

Views: 49

Answers (1)

Temani Afif
Temani Afif

Reputation: 272965

If the number is limited you can approximate like below:

:root {
  --base:10px;
}
.demo {
  font-size:var(--base);
}
.demo ~ .demo {
  font-size:calc(2*var(--base));
}
.demo ~ .demo ~ .demo {
  font-size:calc(3*var(--base));
}
.demo ~ .demo ~ .demo ~ .demo{
  font-size:calc(4*var(--base));
}
.demo ~ .demo ~ .demo ~ .demo ~ .demo{
  font-size:calc(5*var(--base));
}
.demo ~ .demo ~ .demo ~ .demo ~ .demo ~ .demo{
  font-size:calc(6*var(--base));
}
.demo ~ .demo ~ .demo ~ .demo ~ .demo ~ .demo ~ .demo{
  font-size:calc(7*var(--base));
}
<div class="demo">text</div>
<div class="demo">text</div>
<div class="demo">text</div>
<div class="demo">text</div>
<div class="demo">text</div>
<div class="demo">text</div>
<div class="demo">text</div>

Upvotes: 1

Related Questions