DEV Community

CMarghin
CMarghin

Posted on

hide and show nav-links content without using JS (only pure CSS)

I was working on a FreeCodeCamp's project , and I was looking for new ideas even though they only need to perform some simple tasks, accidentally I fond the :target pseudo class in the MDN docs, exactly in the lightbox section

how this selector works

the first thing you should know is that the :target selects the element when its id and the hash in the URL are the same, and that's happens when you visit a link which refers to that element ... for example

if we link a section by an anchor tag

<!-- the link -->
<a href="#changed_element">link</a>

<!-- the linked element -->
<section id="changed_element">
    the changed element
</section> 
Enter fullscreen mode Exit fullscreen mode

now let's change the section's style when the user click on the link that refers to it by adding the :target selector.

#changed_element:target{
    background-color: #000;
    color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

so this selector selects the visited elements

hmmmm so if we want to hide and show elements using this selector we only need to specify their display before and after clicking on their links

example

<!-- nav links -->
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#services">Services</a></li>
</ul>


<section id="home">
    home's content
</section>


<section id="about">
    about's content
</section>


<section id="services">
    services's content
</section>
Enter fullscreen mode Exit fullscreen mode
/* the default display by hiding the elements  */

#home, #about, #services{
    display: none;
}

/* showing the element that has been clicked in the nav-linkd */

#home:target, #about:target, #services:target{
    display: block;
}
Enter fullscreen mode Exit fullscreen mode

so if the user click on a link .. the browser will show the hidden content of that link ... and if he click on other element, the previous element will be hidden again cause he is not targeted and the new link's content will appear

you can change the styles that you want this is just an example ... you can visit this website to see how he made a full website with a single html file
this is my first article in a dev community SO I'm sorry if my explanation was bad (maybe) ... i hope that this article is useful to you and you like it

resources

Top comments (0)