Search code examples
javascriptcssmedia-queriesnav

Make Element Appear On Minimum Screen Size


I have a bug in my header when I shrink the screen size down. The nav is supposed to disappear (only to reappear if the mobile nav icon is clicked,) which is working fine. However, if I click the mobile nav icon, and then click it again to hide it, the nav stays hidden even when I expand the screen size out again.

I want the nav to show up again when the screen gets to 670px.

CSS

@media screen and (min-width: 671px) {
.nav {
    display: block;
    }   
}

@media screen and (max-width: 670px) {
.navicon {
    display: block;   
}
.homeiconcontainers {
    float: none;
    width: 100%;
}
.header {
    background: none;
    opacity: 1;
}
.pagelinkcontainers {
    float: none;
    line-height: 50px;
    background-color: black;
    width: 200px;
    padding-right: 0px;
    text-align: center;
}
ul {
    padding-left: 20px; 
}
.nav {
    display: none;
}   
}

JavaScript

// Show Mobile Navbar Onclick

function MobileMenu (object) {

var elements={"nav":{title: "nav"}};
var mobiledisplay = window.getComputedStyle(document.getElementById("nav")).display;

//Show nav element
for(var nav in elements) {

    if(object!==nav) {

        document.getElementById(nav).style.display='none';
    }
    if(object==nav && mobiledisplay=='block') {

        document.getElementById(nav).style.display='none';   
    }
    else {

        document.getElementById(nav).style.display='block';
        location.hash=pages[nav].title;
        document.title=pages[nav].title;
    }
}
}

My .nav is somehow getting display: none from either my 670px media query, or from the javascript function. I could also be mis-using the min-width media query, but I'm not sure.

Im assuming you don't need to see my HTML to figure this out, but if you would like to, let me know.


Solution

  • Now CSS takes precedence over the JavaScript inline styling forcing the nav bar to be visible.

    @media screen and (min-width: 671px) {
    .nav {
        display: block !important;
    }  
    

    Why? JavaScript code setting inline styling wins from CSS styling. Or better said always takes priority to CSS rules except when that CSS rule has !important.