Karen C
Karen C

Reputation: 47

Mobile Nav dropdown doesn't disappear after resizing window

The mobile nav icon disappears just fine to reveal the desktop nav when I expand the window, but the mobileNavSections div doesn't disappear when it's greater than the specfied screen width. The toggling function works as intended.

function displayMobileNav(){
  var x = document.getElementById("mobileNavSections");
  if (x.style.display == "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
.mobileNav {
  display: none;
}

#mobileNavSections {
  display: none;
  background-color: white;
  position: fixed;
  z-index: 1;
  margin-top: 60px;
  width:100%;
  height: flex;
}

#mobileNavSections a {
  display:block;
  color: black;
  margin: 5%;
  text-decoration: none;
  font-size: 17px;
  opacity:0.5;
}

#mobileNavSections a:hover {
  opacity: 1;
} 


@media only screen 
  and (max-width: 768px){
    .mobileNav{
      display: block;
    }

    .mobileNav img {
      height: 30px;
    }

    .mobileNav:hover {
      cursor: grab;
    }
}
<nav>
  <div class="mobileNav" onclick="displayMobileNav()">
    <img src="images/menuicon.svg">
  </div>
</nav>
<div id="mobileNavSections">
  <a href="#About">About</a>
  <a href="#Contact">Contact</a>
  <a href="#">中文</a>
</div>

Upvotes: 2

Views: 68

Answers (1)

Heather New
Heather New

Reputation: 128

Adding this css media query should finish hiding the nav part that you are not covering with the JS

@media screen and (min-width: 769px){
     #mobileNavSections{
          display:none;
     }
}

I would definitely recommend more of a mobile first when putting together the css. Media queries and overrides can quickly become a headache. Here are some tips and further reading:

Mobile first CSS is written like this:

Styles for mobile and styles that are common to all screen sizes

(no media query)

[icon name=icon-arrow-down]

Media query with a smallish min-width breakpoint

e.g. @media (min-width: 400px)

[icon name=icon-arrow-down]

Media query with a slightly larger min-width breakpoint

e.g. @media (min-width: 600px)

[icon name=icon-arrow-down]

Media query with a larger still min-width breakpoint

e.g. @media (min-width: 960px)

One way to think of it is that you start with a mobile base and build up (or out, if you think in terms of widths).

https://www.mightyminnow.com/2013/11/what-is-mobile-first-css-and-why-does-it-rock/

Upvotes: 1

Related Questions