tabindex-ed 和 focus-ed 容器内的链接不起作用

问题描述

假设我们有一个 HTML 简单的汉堡包导航区域,像这样

<!-- the navigation container  -->
<nav class="hamburger" tabindex="0">
    <!-- a svg icon -->
    <img src="img/menu2.svg">
    <!-- the links container,hidden at startup and showed on :focus on .hamburger container -->
    <div class="items">
        <a href="home.html">home</a>
        <a href="portfolio.html">portfolio</a>
        <a href="contacts.html">contacts</a>
    </div>
</nav>

现在,在 .hamburger 容器上使用 tabindex 和 CSS :focus 伪类,我可以在单击时打开菜单;每次点击链接或导航区域外都会按预期关闭菜单

.hamburger {
    background-color: #789;
    left: 0;
    position: fixed;
    top: 0;
}

.hamburger img {
    outline: none;
    padding: 5px;
    vertical-align: bottom;
    width: 50px;
}

.hamburger .items {
    display: none;
}

.hamburger:focus .items {
    display: block;
}

.hamburger a {
    color: #fff;
    display: block;
    padding: 5px 12px;
    text-decoration: none;
}

.hamburger a:hover {
    background-color: #345;
}

唯一的问题是链接(和按钮)不再起作用:点击链接只是关闭菜单,而不遵循 href。

我知道我可以在复选框/标签上使用 :checked 伪类,但我想知道是否有人知道这种行为的原因,并希望有一个解决方案可以使链接在以下位置再次处于活动状态:像这样的聚焦容器。

非常感谢每一个提示

解决方法

经过多次尝试,我现在可以回答我自己的问题了。

一切都按预期进行,只需将伪类 :focus 替换为 :focus-within,以解决某些元素的容器获得焦点。

所以替换CSS

.hamburger:focus .items {
    display: block;
}

.hamburger:focus-within .items {
    display: block;
}

为我解决了问题。