Hiding and showing element based on screen size

You need to add !important to the CSS property, like:

 #menu { display:block!important; } 

Your Javascript adds style attribute to the element, which has higher priority than any internal or external CSS styles, unless they "are" !important.

What you can also consider doing to avoid that is to toggle some CSS class in your Javascript instead of setting style attribute. This way you avoid using !important.


I suggest to not set an elements style like that, toggle a class on the element is the recommended way

Side note, I also changed from id to class, which is also recommended

Also, specificity is the reason, pointed out already in comments/answers, why your code doesn't work, more to read here: https://developer.mozilla.org/en/docs/Web/CSS/Specificity

var b = document.querySelector(".menu-button");
b.addEventListener("click", function(e) {
  document.querySelector(".menu").classList.toggle("show");
});
.menu {
  display: none;
}
.menu.show {
  display: block;
}


@media screen and (min-width:640px) {
    .menu {
        display: block;
    }
}
<div class="menu show">Hi, I'm a menu element</div>
<button class="menu-button">Show/Hide</button>


Connexo has pointed out the answer but an expansion may be of some use to you and others who come here in the future.

The 'style' of an HTML element can be set in at least 3 places. The browser will have to decide which should win should there be a clash. The rules used are called 'specificity'. There is a good article on this topic here https://css-tricks.com/specifics-on-css-specificity/ if you want a fuller explanation.

Roughly, any styling defined in the initial HTML 'style' attribute is most powerful so this will win in over a CSS file rule. Importantly, setting the style as you have done in your use case, operates on the HTML style attribute.

Therefore, your CSS is being overruled by the style attribute setting in your code.

For a pure JS solution you could look at adding a listener to the window onResize event. If you do research that approach please be aware that in some browsers the event fires for every pixel of the size change, so look for a solution that takes that into consideration like this one otherwise the function will be triggered multiple times and may reduce the joy you bring to your users.