How can I create a full screen target for CSS-only navigation menus using: target?

Linked to this StackOverflow question, although the question seems to be poorly formulated and therefore hasn't received any answers.

I'm looking to create a progressive enhancement navigation menu in mobile-first design so :hover

not an option. The first step is to implement a free navigation JavaScript dropdown menu using a pseudo selector :target

. I'll add a JavaScript solution on top of this later. The menu will be on a public website that requires support for users who have JS disabled.

Opening the menu without problems - my question comes up when you need to close the menu. The only way to do this is to remove the id from the url hash.

For example, a menu appears when you click the following link: <a href="#nav">Menu</a>

which changes the url to www.something.com/#nav

. To hide the menu, I need to remove #nav

from the url. The solution is to add another link that changes the hash: <a href="#top">Close Menu</a>

.

The user will expect that clicking anywhere outside of the menu will close the menu. The first solution that comes to mind is to use a little z-index magic to create a full screen anchor tag just below my menu.

Open to suggestions and other solutions.

HTML:

<header id="top">
    <a href="#nav" class="toggle-nav">Menu</a>

    <ul id="nav">
        <li><a href="#top">Close Menu</a></li>
        <li><a href="#">Nav Item 1</a></li>
        <li><a href="#">Nav Item 2</a></li>
        <li><a href="#">Nav Item 3</a></li>
    </ul>
</header>

      

SCSS:

#nav {
    position: relative;
    z-index: 2;

    &:not(:target) {
        display: none;
    }

    &:target {
        display: block;
    }

}

      

+3


source to share


1 answer


You can do this using checkbox

both show and hide navigation with a selector :checked

.

JSFiddle - DEMO 1 and DEMO 2

HTML:



<header id="top">
    <label for="toggle-1">Menu</label>
    <input type="checkbox" id="toggle-1">
    <ul id="nav">
        <li><a href="#top">Close Menu</a></li>
        <li><a href="#">Nav Item 1</a></li>
        <li><a href="#">Nav Item 2</a></li>
        <li><a href="#">Nav Item 3</a></li>
    </ul>
</header>

      

CSS

input[type=checkbox] {
    position: absolute;
    top: -9999px;
    left: -9999px;
}
input[type=checkbox]:checked ~ ul#nav {
    display: block;
}
#nav {
    display: none;
}
label {
    cursor: pointer;
}

      

+2


source







All Articles