Unable to change the display of a div using the :target pseudo class

74 views Asked by At

I am trying to change the display of a div using the CSS :target pseudo class.

Here is the fiddle with a small portion of the code that I am trying to implement : https://jsfiddle.net/Lparay7r/

HTML

<div id="navbarContent" class="navbarContent">
            <ul>
                <li><a href="#doodles" id="navbarHome">Home</a></li>
                <li><a href="../about/">About</a></li>
                <li><a href="#servicesNavToggleOptions" class="servicesNavToggleLink">Services</a></li>
                <div id="servicesNavToggleOptions">
                    <li><a href="../doodle_art/">Doodle Art</a></li>
                    <li><a href="../illustrations/">Illustrations</a></li>
                    <li><a href="../paintings/">Paintings</a></li>
                    <li><a href="../graphic_design/">Graphic Design</a></li>
                </div>
                <li><a href="#">Products</a></li>
                <li><a href="../contact/">Contact</a></li>
            </ul>
</div>  

CSS

div.navbarContent ul div#servicesNavToggleOptions:not(:target) {
display: none;
}

div.navbarContent ul div#servicesNavToggleOptions:target {
display: block;
}

JavaScript

var div = document.getElementById('servicesNavToggleOptions');
div.style.display = "none";

So, intially JavaScript sets the display of the div to none. When the 'services' link is clicked, I expect the display of the div to become 'block' as it is being targetted.

That is not happening. I do not understand why the div is not getting displayed?

PS: I am new at programming, so please bear with any ignorance.

1

There are 1 answers

1
Dekel On BEST ANSWER

Your problem is that the #servicesNavToggleOptions element still have the inline display: none (which takes over the css block definition).

You can use this the !important to override it:

div.navbarContent ul div#servicesNavToggleOptions:target {
    display: block !important;
}

https://jsfiddle.net/dekelb/fL17y3g9/

var div = document.getElementById('servicesNavToggleOptions');
div.style.display = "none";
div.navbarContent ul div#servicesNavToggleOptions:not(:target) {
  display: none;
}
div.navbarContent ul div#servicesNavToggleOptions:target {
 display: block !important;
}
<div id="navbarContent" class="navbarContent">
  <ul>
    <li><a href="#doodles" id="navbarHome">Home</a></li>
    <li><a href="../about/">About</a></li>
    <li><a href="#servicesNavToggleOptions" class="servicesNavToggleLink">Services</a></li>
    <div id="servicesNavToggleOptions">
      <li><a href="../doodle_art/">Doodle Art</a></li>
      <li><a href="../illustrations/">Illustrations</a></li>
      <li><a href="../paintings/">Paintings</a></li>
      <li><a href="../graphic_design/">Graphic Design</a></li>
    </div>
    <li><a href="#">Products</a></li>
    <li><a href="../contact/">Contact</a></li>
  </ul>
</div>