我正在尝试仅使用HTML和CSS制作汉堡菜单。我从https://www.youtube.com/watch?v=xMTs8tAapnQ开始尝试了。现在我不知道为什么我的代码无法正常工作。
header{
background-color: #f1f1f1;
text-align: center;
}
.inline{
display: flex;
justify-content: space-around;
align-items: center;
}
header .primary #toggle{
display: none;
}
header .primary #toggle:checked ~ header .primary nav{
display: block;
}
header .primary label{
font-size: 2.25rem;
display: block;
cursor: pointer;
}
header .primary nav{
display: none;
}
header nav ul{
font-size: 1.25rem;
}
header .primary nav ul li{
padding: 1rem;
}
header nav ul li a{
text-decoration: none;
color: #000000;
}
header nav ul li.active{
border-bottom: 2px solid black;
margin: 0 5%;
}
<header>
<div class="primary">
<div class="inline">
<img src="./image/logo.png" alt="LOGO">
<input type="checkbox" id="toggle">
<label for="toggle">☰</label>
</div>
<nav>
<ul>
<li class="active"><a href="./index.html">Home</a></li>
<li><a href="./about.html">About</a></li>
<li><a href="./contact.html">Contact</a></li>
</ul>
</nav>
</div>
</header>
答案 0 :(得分:1)
#toggle:checked ~ header .primary nav
在<nav>
内部的class="primary"
内部将<header>
定位为#toggle:checked
的后续同级。
因此,您需要将<input>
放在<header>
之前,像这样:
<input id="toggle" type="checkbox">
<header>
<div class="primary">
<nav>...</nav>
</div>
</header>
工作示例:
header {
background-color: #f1f1f1;
text-align: center;
}
.inline {
display: flex;
justify-content: space-around;
align-items: center;
}
#toggle {
display: none;
}
header .primary label {
font-size: 2.25rem;
display: block;
cursor: pointer;
}
header .primary nav {
display: none;
}
#toggle:checked~header .primary nav {
display: block;
}
header nav ul {
font-size: 1.25rem;
}
header .primary nav ul li {
padding: 1rem;
}
header nav ul li a {
text-decoration: none;
color: #000000;
}
header nav ul li.active {
border-bottom: 2px solid black;
margin: 0 5%;
}
<input type="checkbox" id="toggle">
<header>
<div class="primary">
<div class="inline">
<img src="./image/logo.png" alt="LOGO">
<label for="toggle">☰</label>
</div>
<nav>
<ul>
<li class="active"><a href="./index.html">Home</a></li>
<li><a href="./about.html">About</a></li>
<li><a href="./contact.html">Contact</a></li>
</ul>
</nav>
</div>
</header>
MDN:CSS combinators。
W3C(官方规格):subsequent sibling combinator。