Reputation: 407
I'm trying to use the CSS counter to create Chapter numbers. As you can see in the example below, it's working properly if I deal with classes inside a container, but doesn't work when I try to use it in subitems inside div. Any idea how to correct this behavior ? (I need to use this kind of structure)
.itemsContainer {
counter-reset: section;
}
.t1 {
counter-reset: subsection;
}
.t1:before {
counter-increment: section;
content: counter(section) ". ";
}
.t2:before {
counter-increment: subsection;
content: counter(section) "."counter(subsection) " ";
}
<h3>Direct access to class</h3>
<div class="itemsContainer">
<p class="t1"></p>
<p class="t2"></p>
<p class="t2"></p>
</div>
<h3>Inside div</h3>
<div class="itemsContainer">
<div class="item">
<p class="t1"></p>
</div>
<div class="item">
<p class="t2"></p>
</div>
<div class="item">
<p class="t2"></p>
</div>
</div>
Upvotes: 5
Views: 393
Reputation: 14844
Error here come from the rule:
.itemsContainer {
counter-reset: section;
}
So each time that you have an .itemsContainer
element the counter section
is going to be reset.
To avoid this just say that only the first .itemsContainer
element reset the counter:
.itemsContainer:nth-of-type(1) {
counter-reset: section;
}
For the "Inside div" part you will need to increment the subsection
using .item
and not .item .t2
. Don't forget that the first element don't have to increment the counter. In css you can use the :not()
property for that:
.item:not(:first-child) {
counter-increment: subsection;
}
Please check the demo:
.itemsContainer:nth-of-type(1) {
counter-reset: section;
}
.itemsContainer .t1 {
counter-reset: subsection;
}
.t1::before {
counter-increment: section;
content: counter(section) ". ";
}
.item:not(:first-child) {
counter-increment: subsection;
}
.itemsContainer>.t2::before {
counter-increment: subsection;
content: counter(section) "."counter(subsection) " ";
}
.itemsContainer>.item>.t2::before {
content: counter(section) "."counter(subsection) " ";
}
<h3>Direct access to class</h3>
<div class="itemsContainer">
<p class="t1"></p>
<p class="t2"></p>
<p class="t2"></p>
</div>
<h3>Inside div</h3>
<div class="itemsContainer">
<div class="item">
<p class="t1"></p>
</div>
<div class="item">
<p class="t2"></p>
</div>
<div class="item">
<p class="t2"></p>
</div>
</div>
For further details just check the W3C documentation: https://www.w3schools.com/CSS/css_counters.asp
Upvotes: 2