Search code examples
htmlcssresponsive

How to appear element at X px, in this case?


@media screen and (max-width: 670px) {

    #hamburger {
        display: block;
    }

}

#hamburger {
    display: none;
}

but this doesn't work (#hamburger never appears) so I don't know what to do because in theory the code is supposed to work, here is another part of the code

#hamburger {
    display: none;
}

.navbar .checkbox {
    position: absolute;
    display: block;
    height: 32px;
    width: 32px;
    top: 20px;
    right: 20px;
    z-index: 5;
    opacity: 0;
    cursor: pointer;
  }

.navbar .hamburger-lines {
    display: flex;
    height: 26px;
    width: 32px;
    position: absolute;
    top: 17px;
    right: 20px;
    z-index: 2;
    flex-direction: column;
    justify-content: space-between;

    opacity: 1;
    transition: opacity 0.2s ease;
  }

the error may be in there but I don't understand

here is the html

<nav class="navbar">
        <ul>
            <li><a href="#Home">HOME</a></li>
            <li><a href="#Skills">SKILLS</a></li>
            <li><a href="#Portfolio">PORTFOLIO</a></li>
            <li><a href="#AboutMe">ABOUT ME</a></li>
        </ul>

        <div id="hamburger">
            <input class="checkbox" type="checkbox" name="" id="" />

            <div class="hamburger-lines">
                <span class="line line1"></span>
                <span class="line line2"></span>
                <span class="line line3"></span>
            </div>  
        </div>

if necessary : https://github.com/August7337/website


Solution

  • The order of CSS rules is important when two rules have the same specificity. The #hamburger rule inside the media query is before the one without, so the display: none will always take precedence. Instead, reorder the rules so that the rule within the media query is after the one without:

    #hamburger {
      display: none;
    }
    
    @media screen and (max-width: 670px) {
      #hamburger {
        display: block;
      }
    }
    <nav class="navbar">
      <ul>
        <li><a href="#Home">HOME</a></li>
        <li><a href="#Skills">SKILLS</a></li>
        <li><a href="#Portfolio">PORTFOLIO</a></li>
        <li><a href="#AboutMe">ABOUT ME</a></li>
      </ul>
    
      <div id="hamburger">
        Hamburger
      </div>
    </nav>