As Carlos Mateo has already mentioned, your CSS does not have enough specificity to overcome the inline style added by jQuery.
jQuery hides the navigation by adding an inline style directly to the element; your CSS applies shows the navigation by using an ID selector. Referencing the CSS specificity chart below, note that inline styles have higher specificity than ID selectors (emphasis and bold added by me).
Selector Types
The following list of selector types is by increasing specificity:
- Universal selectors (e.g., *)
- Type selectors (e.g., h1)
- Class selectors (e.g., .example)
- Attributes selectors (e.g., [type="radio"])
- Pseudo-classes (e.g., :hover)
- ID selectors (e.g., #example)
- Inline style (e.g., style="font-weight:bold")
Source: Specificity @ MDN
Carlos Mateo's solution is simple and works well. If it works in the context of your project, I highly recommend it. However, there are situations in which you may not want to use !important
. It has its drawbacks, some of which are mentioned here. For this reason, I'm providing an alternate solution.
In my example below, I'm using the callback of jQuery's slideToggle()
to remove the inline style and replace it with a CSS class after the slide is complete. This gives you the freedom to override CSS definitions without using !important
.
NOTE: Use the "Full Page" button to test the action of the media query.
$(document).ready(function() {
$("#toggle").click(function() {
$("#nav").slideToggle(500, function() {
$(this).toggleClass('shown'); /* Toggle "display" class */
$(this).removeAttr('style'); /* Remove style attribute */
});
});
});
#nav {
display: none;
}
#nav.shown {
display: block;
}
#toggle {
background-color: #FF9;
width: 100%;
}
#toggle::after {
content: "≡";
float: right;
}
@media only screen and (min-width: 500px) {
#nav {
display: block;
}
#toggle {
display: none;
}
#nav li {
float: left;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toggle">menu</div>
<div id="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Support</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>