I am trying to create a navigation bar. When the screen size becomes a certain size, I want the tab links to disappear and a button appears to make them expand. This is working as intended, however while I have pushed the button and I have the expanded list, if my screen size changes and increases above the threshold the changes still apply and I can’t find a way to remove them.
The code:
HTML:
<nav>
<div class="navList">
<ul>
<li class = "navImg"><img src="./Images/Logo (1).png" alt="Logo" /></li>
<li><a href="#">Home</a></li>
<li><a href="#">Collection</a></li>
<li><a href="#">Wholesale</a></li>
<li><a href="#">Contact</a></li>
</ul>
<button class="navDropdown">☰</button>
</div>
</nav>
CSS:
.navList {
display: flex;
background-color: #002F63;
}
.navList ul {
display: flex;
margin-bottom: 0;
}
.navList ul li {
list-style: none;
margin: 1.7rem;
margin-top: 2.5rem;
font-size: 1.5rem;
}
.navImg {
padding: 0;
margin: 0 !important;
margin-left: 1rem !important;
margin-right: 1rem !important;
}
.navList ul li a {
text-decoration: none;
color: white;
}
.navDropdown {
align-self: right;
margin-left: auto;
background-color: #002F63;
border: none;
color: white;
padding-right: 1.5rem;
font-size: 1.5rem;
display: none;
}
@media (max-width: 813px) {
.navList ul{
display: none;
}
.navDropdown {
display: inline-block;
}
}
Javascript:
$(".navDropdown").on("click", function () {
var x = $(".navList ul").css("display");
if (x === "none") {
$(".navList ul").css("display","block");
} else {
$(".navList ul").css("display","none");
}
});
I want the navigation bar to return to normal when increasing the screensize after I have pressed the button, but it remains as expanded.
2
Answers
You could consider toggling a class on the
<ul>
element instead of applying CSS directly on the element. Using a class lets you apply the same CSS but then you can have it only activate within your media query constraint:I probably have too much CSS; as you can tell I have a preference for kebab
my-class
css style names.No need for jQuery here so I just used plain JavaScript to toggle a
show-me
class and put that in the media query where the width is narrow so the button "overrides" the media query that way.Note I put a small font on the
img
so it did not look bad when no image was present.I put some ugly borders on just to show what is where.
Converted the px to em and set the normal browser default of 16px = 1em