Media Query Styles Not Overriding Original Styles

Ben Black picture Ben Black · Sep 26, 2013 · Viewed 66.2k times · Source

I'm attempting to use some media queries for a website I'm building. The problem I'm having however, is while the media query styles are actually being applied, they're being overridden. I can't for the life of me tell why because I'm using the same exact selectors. Can anyone point out something that I'm not seeing?

ORIGINAL CSS

#global-wrapper-outer > #global-wrapper-inner {
    width: 85%;
    height: 100%;
    margin: 0 auto;
    position: relative;
}
    #global-wrapper-outer > #global-wrapper-inner > nav {
        background: #fff;
        padding-bottom: 20px;
        box-shadow: 0 4px 2px -2px gray;
    }

MEDIA QUERY CSS

@media screen and (max-width:1024px) {
    #global-wrapper-outer > #global-wrapper-inner {
        width: 100%;
    }
    #global-wrapper-outer > #global-wrapper-inner > nav {
        display: none;
    }
}

The second media query is working fine, where I set the nav to have a display of none. However, when I try to set the width of #global-wrapper-inner to 100% it doesn't apply. I can see the style being "applied" when I press F12 and select that element. However, the style itself is crossed out and not actually applied and it still has the original width of 85%.

Answer

Jason Yaraghi picture Jason Yaraghi · Sep 26, 2013

The selectors in your original CSS have the same specificity as the selectors within your media queries (the first declarations are also targeting the same property - width) and because the media query rule set is being overridden I'm going to assume that it appears before the original rule set.

The second media query selector works because it's targeting a property that wasn't set in your original CSS, so specificity isn't relevant.

To have the first media query selector take precedence, prepend an ancestor element to it:

@media screen and (max-width:1024px) {
    body #global-wrapper-outer > #global-wrapper-inner {
         width: 100%;
    }
    #global-wrapper-outer > #global-wrapper-inner > nav {
        display: none;
    }
}