I have a page name url.com/yourfirstpage/ when i go to the page all the div are hidden by default (display:none) if we target #sec1 as url.com/yourfirstpage/#sec1 it only displays sec1 and hide others. I was wondering if we go the url without having anchor id like url.com/yourfirstpage/ it needs to show all the divs.
#sec1, #sec2, #sec3{
display:none;
}
#sec1:target{
display:block;
}
#sec2:target{
display:block;
}
#sec3:target{
display:block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</div>
Here is a trick in case you are able to modify your HTML structure. The idea is to have the elements visible and then we hide them using :target
. Since we don't have previous sibling selector or parent selector, I used id within a parent element to be able to select any 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>
It can work with any number of sections and we can improve the CSS code as follow:
#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>
this quick approach may help
you can do with !
selector in CSS by using postcss plugins
[...document.querySelectorAll('a')].forEach(a => {
a.addEventListener('click', () => {
a.parentElement.classList.add('targeted')
})
})
.targeted div {
display: none;
}
.targeted div:target {
display: block;
}
<a href="#sec1">sec1</a>
<a href="#sec2">sec2</a>
<a href="#sec3">sec3</a>
<div id="sec1" class="page"> this is sec1</div>
<div id="sec2" class="page"> this is sec2</div>
<div id="sec3" class="page"> this is sec3</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With