简体   繁体   中英

My Responsive Navigation Bar Doesn't functioning well

I have made a responsive navigation bar for Mobile screen but it's not working well. It gets shrink when its come to the mobile screen but when I clicked on icon nav bar doesn't expand on the mobile screen. The click icon button doesn't work on when comes on mobile screen. My code is here. Please help..

<body>

        <div class="first" id="myfirst">
            <a href="#home">Home</a>
            <a href="#news">News</a>
            <a href="#contact">Contact</a>
            <a href="#about">About</a>
            <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
        </div>
      </body>

    .first  a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }

    .first  a:hover {
      background-color: #ddd;
      color: black;
    }

    .first  .icon {
      display: none;
    }

    @media screen and (max-width: 600px) {
      .first  a:not(:first-child) {display: none;}
      .first  a.icon {
        float: right;
        display: block;
      }
    }

    @media screen and (max-width: 600px) {
      .responsive {
          position: relative;
        }
      .responsive .icon {
        position: absolute;
        right: 0;
        top: 0;
      }
      .responsive a {
        float: none;
        display: block;
        text-align: left;
      }

    }    

The effect is not as desired because CSS is C ascading and .first a:not(:first-child) selector has more priority then .responsive a one.

So, the quickest way to fix your code is to change last .responsive a selector in this way:

.responsive a:first-child,
.responsive a:not(:first-child) {
  float: none;
  display: block;
  text-align: left;
}

Finally, just a couple of suggestions:

  • is better to use nav HTML5 element instead of div : it strengthen code semantics
  • avoid identical @media screen and (max-width: 600px) { media queries: it weakens readability and maintainability
  • improve class semantics giving more suitable names (eg: rename responsive in open )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM