Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a :target tag

Tags:

html

css

I have been using css3 and the target attribute to make an interactive menu. When i click a menubutton, i make it open the sub-menu by using the :target attribute. I simply say that when my menu point is the target, set the submeny height to auto, if its not the target, it should have a height of 0.

But now is my question: Is there an easy way to remove the target again? What i want to do, is that when i click the menu button, the submenu will show (I already made that). Then if i click the same button again, i want is to close again.

Is there a way to do this with pure css/html, or will i need to change to javascript/jquery to do this? I used css3 to avoid this so far.

like image 333
Nick Avatar asked Sep 02 '25 02:09

Nick


1 Answers

You can create an absolutely positioned link to another anchor that appears in front of the link to your :target, and make it display only if the current :target works. So visually it will behave as a toggle link (see fiddle):

HTML

<div id="test">
    <h2>
        <a href="#test">Open me</a>
        <a href="#" class="untarget"></a>
    </h2>
    <div>
        <p>Some contents</p>
        <p>Some more contents</p>
        <p>Some more contents again</p>
    </div>
</div>

The key part of CSS

h2 {
    position: relative;
    display: inline-block;
}

.untarget {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    display: none;
}

:target .untarget {
    display: block;
}

Another (and quite popular) way to implement the toggle functionality without JS is using hidden checkboxes/radio buttons and their :checked pseudo-class along with CSS sibling combinators. But personally I doubt if it the right way of HTML usage.

like image 151
Ilya Streltsyn Avatar answered Sep 05 '25 00:09

Ilya Streltsyn