CSS :checked ~ ul 伪类不起作用

问题描述

我已经阅读了所有关于此的类似帖子,但没有一个我有用。

我正在尝试使用一些 YouTube 教程制作响应式导航栏,我有一个复选框可以在宽度很小时隐藏显示菜单。我已经看到控制台在寻找错误,但没有错误,我已经将浏览器从 chrome 更改为 edge 和 firefox,但它似乎也不是浏览器。此外,我更改了 HTML 中的标签顺序以完成兄弟一般的某事规则,但没有任何效果我有点卡住了。

下面是我的 HTML 代码

<header>
        <nav>
            <img class="logo" src="/responsive1/logo.svg" alt="logo">
            <input type="checkBox" class="check">
            <label for="check" class="checkbtn">
                <i class="fas fa-bars"></i>
            </label>
            <ul>
                <li><a href="#" class="active">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Services</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </header>

这是我想用来隐藏和显示菜单的 CSS 代码

@media (max-width: 858px) {

ul {
        position: fixed;
        width: 100%;
        height: 100vh;
        background: #2c3e50;
        top: 80px;
        left: -100%;
        text-align: center;
        transition: all .5s;
    }

.check:checked~ul{
        left: 0;
    }
}

这里的一个相关细节是,当我添加 ~ 字符,然后单击

这是我正在学习的教程,他在 6:30 分钟内完成的确切部分: https://www.youtube.com/watch?v=oLgtucwjVII

如果有帮助,这里是所有 CSS 代码

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');
* {
    padding: 0px;
    margin: 0px;
    text-decoration: none;
    list-style: none;
    Box-sizing: border-Box;
    font-family: "Montserrat",sans-serif;
}

body header {
    background-color: #0082e6;
    height: 80px;
    width: 100%;
}

.logo {
    width: 150px;
    line-height: 80px;
    margin: 15px 100px;
    cursor: pointer;
}

nav ul {
    float: right;
    margin-right: 20px;
}

nav ul li {
    display: inline-block;
    line-height: 80px;
    margin: 0 5px;
}

nav ul li a {
    color: white;
    font-size: 17px;
    padding: 7px 13px;
    border-radius: 3px;
    text-transform: uppercase;
}

a .active,a:hover {
    background-color: #1b9bff;
    transition: .5s;
}

.checkbtn {
    font-size: 30px;
    color: white;
    float: right;
    line-height: 80px;
    margin-right: 40px;
    cursor: pointer;
    display: none;
}

.check {
    display: none;
}

@media (max-width: 952px) {
    .logo {
        width: 100px;
        margin: 25px 50px;
    }
    nav ul li a {
        font-size: 16px;
    }
}

@media (max-width: 858px) {
    .checkbtn {
        display: block;
    }
    ul {
        position: fixed;
        width: 100%;
        height: 100vh;
        background: #2c3e50;
        top: 80px;
        left: -100%;
        text-align: center;
        transition: all .5s;
    }
    nav ul li {
        display: block;
        margin: 50px 0;
        line-height: 30px;
    }
    nav ul li a {
        font-size: 20px;
    }
    a:hover,a.active {
        background-color: none;
        color: #0082e6;
    }
    .check[type=checkBox]:checked~ul {
        left: 0;
    }
}

解决方法

我正在使用标签 class="check"> 和属性