0

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.

InSync
  • 4,851
  • 4
  • 8
  • 30
poltergaz
  • 27
  • 5
  • 3
    `#check:checked ~ ul` means select an `
      ` that is preceded (not necessarily immediately) by a `:checked` element that has an `id` of `check`. Your `
        ` 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`.
    – InSync May 31 '23 at 13:12
  • 1
    Does this answer your question? [What does the "~" (tilde/squiggle/twiddle) CSS selector mean?](https://stackoverflow.com/questions/10782054/what-does-the-tilde-squiggle-twiddle-css-selector-mean) – InSync May 31 '23 at 13:13
  • You need to alter your HTML so that the ul comes after the input. – A Haworth May 31 '23 at 13:19
  • Yeah, I was using it the wrong way... and now I find out there is no way to select previous sibling or previous parent, That's another problem because I need ```#checkbox``` after ```
      ```, but I'll try to find a way around that.
    – poltergaz Jun 01 '23 at 00:08

0 Answers0