Search code examples
cssresponsive-designmedia-queries

@media queries - one rule overrides another?


I have multiple @media queries all working fine but as soon as i put in a higher max screen-width than 1024px the rules for the higher width gets applied to everything.

    @media screen and (max-width: 1400px)
    {
        #wrap {
        width: 72%;
        }
    } 
@media screen and (max-width: 1024px) 
{
    #slider h2 {
    width: 100%;
    }
    #slider img {
    margin: 60px 0.83333333333333% 0 2.08333333333333%;
    }
    .recent {
    width: 45.82%;
    margin: 10px 2.08333333333334% 0 1.875%;
    }
}

as you can see 1024px (and also the 800px max-width query) do not change the #wrap width and work fine. As soon as i add the 1400px max-width query it changes them to 72% for ALL sizes and does the same for any element - for instance if i set #slider img to have a margin of 40px it will show at ALL sizes even though it is only in the max-width of 1400px.

Am i missing something really obvious? Been trying to work this out for the past 2 days! Thanks, John


Solution

  • I'm not sure I entirely follow, but your @media rules suggest this is the behaviour you want. If the screen is 1400px and lower the width of #wrap will be 72%, this includes all other sizes mentioned in other media queries.

    If you wanted it to only apply between 1024px and 1400px you need to change it to...

    @media screen and (max-width: 1400px) and (min-width: 1024px)
    {
        #wrap {
        width: 72%;
        }
    } 
    

    EDIT You also have to remember that ordering matters in CSS...

    @media screen and (max-width: 1400px)
    {
        #wrap {
        width: 72%;
        }
    }
    @media screen and (max-width: 1024px)
    {
        #wrap {
        width: 100%;
        }
    }
    

    For screens above 1024px the width of #wrap will be 72% as they will only match the first media query. If the screen is below 1024px the width of #wrap will be 100%, although it will be matched by both media queries. The CSS that will be rendered for a screen under 1024px will look like...

    #wrap {
    width: 72%;
    }
    #wrap {
    width: 100%;
    }
    

    Rules defined later in the stylesheet overrides earlier rules http://www.w3.org/TR/CSS21/cascade.html#cascading-order 6.4.1 point 4. Therefore, if you swapped the order of the rules.

    @media screen and (max-width: 1024px)
    {
        #wrap {
        width: 100%;
        }
    }
    @media screen and (max-width: 1400px)
    {
        #wrap {
        width: 72%;
        }
    }
    

    The width of #wrap will be 72% for ALL screen sizes up to 1400px because a screen under 1024px will see both rules as if they were...

    #wrap {
    width: 100%;
    }
    #wrap {
    width: 72%;
    }
    

    A screen over 1024px will see...

    #wrap {
    width: 72%;
    }
    

    Both have the same result.