Search code examples
htmlcsshyperlinkchildrentabindex

Showing/hiding elements inside a div block with HTML and CSS


I would like to show/hide elements inside a div block. A similar post showed me how, but I can't make the links inside the div block work properly.

The div block:

<div   class="collapse"  tabindex="1">
<h1> Test </h1>
<p><a href="www.google.com">link</a></p>
<p>some other text</p>
</div>

The CSS part:

.collapse > * + *{
display:none;
}
.collapse:focus > * + *{
display:block; 
}

Here is a JSFiddle of my script.

Basically, as I click on the link, the div block collapse. Do you know how can I fix this? Thanks!!


Solution

  • You can't do this natively with CSS, you'll have to use JavaScript. Here is my code:

    HTML:

    <h1><a href="#" class="clickme">Test</a></h1>
    <div class="show-on-click">
        <a href="www.google.com">link</a>
        <p>some other text</p>
    </div>
    

    CSS:

    .show-on-click {
        display: none;
    }
    .show-on-click.is-active {
        display: block;
    }
    

    JavaScript (jQuery):

    $(".clickme").on("click", function () {
        $(".show-on-click").toggleClass("is-active");
    });
    

    I hope this all makes sense. Sorry I had to kind of massacre your code to achieve it. I've updated your jsfiddle here.