I've been making a sticky navbar for my site and it has a hamburguer menu on the top right corner. I want to make so that, with only CSS and HTML, the hamburguer menu can hide and show itself using the :checked
pseudo-element.
@media(max-width: 1000px) {
label #btn {
display: block;
}
ul {
position: fixed;
width: 100%;
height: 100vh;
background: #34495e;
top: 80px;
left: -100%;
/*hides navbar*/
text-align: center;
transition: all .5s;
}
nav ul li {
display: block;
margin: 50px 0;
line-height: 30px;
}
nav ul li a {
display: block;
font-size: 20px;
}
/*when user clicks button, change the icon and bring the mobile <ul>*/
#check:checked~ul {
left: 0;
/*not working (doesn't change value of left:)*/
}
#check:checked~label #btn {
display: none;
}
#check:checked~label #cancel {
display: block;
}
}
<ul>
<li><a href="#">ITEM 1</a></li>
<li><a href="#">ITEM 2</a></li>
<li><a href="#">ITEM 3</a></li>
</ul>
<input type="checkbox" id="check">
<!--hamburguer menu-->
<label for="check">
<i class="fas fa-bars" id="btn"></i>
<i class="fas fa-times" id="cancel"></i>
When the page gets shrinked down, the <ul>
goes hidden with left: -100%;
and was supposed to come back with #check:checked ~ ul{left: 0;}
. The problem is that this doesn't work, actually, nothing I write inside that pseudo-element for <ul>
works (like changing the backgroung color for instance). However, #check:checked ~ label #btn
and #check:checked ~ label #cancel
work just fine.
If I type left: 0
on the Firefox Developer Tools, the <ul>
shows up! So I think the problem must be with the #check:checked
pseudo-element.
` that is preceded (not necessarily immediately) by a `:checked` element that has an `id` of `check`. Your `
– InSync May 31 '23 at 13:12` precededs ``, so the selector fails to select anything. That being said, you can either use [`:has()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:has) or move your `#check` to before `ul`.
```, but I'll try to find a way around that.
– poltergaz Jun 01 '23 at 00:08