If you need to adjust your HTML structure, here's a neat trick for you. The concept involves initially displaying the elements and then using :target
to hide them. To achieve this without the ability to select previous or parent elements directly, I utilized an id within a parent element to target any specific element:
#sec1:target .page:nth-child(n+2){
display: none;
}
#sec2:target .page:nth-child(2n+1){
display: none;
}
#sec3:target .page:nth-last-child(n+2){
display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<div id="sec1">
<div id="sec2">
<div id="sec3">
<div class="page"> this is sec1</div>
<div class="page"> this is sec2</div>
<div class="page"> this is sec3</div>
</div>
</div>
</div>
This method can be adapted for numerous sections, with room for enhancing the CSS code as shown below:
#sec1:target .page:not(:nth-child(1)),
#sec2:target .page:not(:nth-child(2)),
#sec3:target .page:not(:nth-child(3)),
#sec4:target .page:not(:nth-child(4)),
#sec5:target .page:not(:nth-child(5)) {
display: none;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<a href="#sec4">sec4</a>
<a href="#sec5">sec5</a>
<div id="sec1">
<div id="sec2">
<div id="sec3">
<div id="sec4">
<div id="sec5">
<div class="page"> this is sec1</div>
<div class="page"> this is sec2</div>
<div class="page"> this is sec3</div>
<div class="page"> this is sec4</div>
<div class="page"> this is sec5</div>
</div>
</div>
</div>
</div>
</div>