Reputation: 125
.menu > .item:nth-child(n+2) {
display: none;
}
.menu:hover > .item,
.menu:focus > .item,
.menu > .item:focus,
.item:focus ~ .item {
display: block;
}
.item:focus {
outline: 3px solid red;
}
<button>Go from here</button>
<div class="menu">
<a class="item" href="#">One</a>
<a class="item" href="#">Two</a>
<a class="item" href="#">Three</a>
</div>
If the cursor is over the menu, everything is tabbed back and forth fine. However, while the menu is hidden, it's not possible to focus none of the hidden elements with Tab. Is it possible to circumvent this?
Worth noting that I'd like it to work even in outdated browsers, so it's not a good idea to resort to modern solutions like :focus-within
(but a JS fallback might be okay; in very old or marginal browsers, nth-child
wouldn't work anyway and the menu would just be always expanded).
Upvotes: 0
Views: 1150
Reputation: 125
The solution is to toggle the hidden part of the menu with an invisible checkbox:
.menu {
position: relative;
}
.menu > input {
position: absolute;
top: 0;
right: 0;
opacity: 0;
z-index: -1;
}
.menu > .item:nth-of-type(1),
.menu > label {
display: inline-block;
}
.menu > .item:nth-of-type(n+2) {
display: none;
}
.menu:hover > .item:nth-of-type(n+2),
.menu > input:checked ~ .item:nth-of-type(n+2) {
display: block;
}
.item:focus, .menu > input:focus ~ label {
outline: 3px solid red;
}
.menu > input:checked ~ label {
background-color: magenta;
}
<button>Go from here</button>
<div class="menu">
<a class="item" href="#">One</a>
<input id="c" type="checkbox" aria-label="Expand/collapse" role="button" />
<label for="c">↓</label>
<a class="item" href="#">Two</a>
<a class="item" href="#">Three</a>
</div>
Thanks to @QuentinC for pointing into this direction.
Upvotes: 0
Reputation: 14687
From the accessibility point of view, you should just stop using :hover to display or hide elements. It's bad for several reasons:
For all these reasons, it's better to forget about :hover and switch to an explicit show/hide toggle, where the state (shown or hidden) don't change without a clear user interaction.
Upvotes: 1