Search code examples
cssmedia-queries

CSS Media Query Execution


I'm having an issue with a CSS media query where the general style is being applied after the media query despite being above the media query in the cascade.

Example:

HTML:

<div id="myblock1">
    <div>Block 1</div>
    <div id="myblock2">Block 2</div>
    <div>Block 3</div>
</div>​

CSS:

#myblock1 div {
    display:block;
    background-color:#F00;
}

@media (min-width:600px) {
    #myblock2 {
        display:none;
    }
}​

Live demo: jsFiddle

In theory, all 3 blocks should be visible in windows of 600px width or less, and when larger the middle block should disappear, but that is not the case. Any ideas on why the ID/media query is being applied before the general styling?


Solution

  • That's because #myblock1 div is more specific than #myblock2 (1 ID + 1 element vs 1 ID).

    You'll either need to be more specific, or add !important on the rule you're trying to override.

    • Be more specific: #myblock1 #myblock2 { display: none; }
    • Use !important: #myblock2 { display: none !important; }

    In my opinion, the best solution would be to make the outer container less specific, by giving it a class name, rather than an ID:

    <div class="myblock1">
        <div>Block 1</div>
        <div id="myblock2">Block 2</div>
        <div>Block 3</div>
    </div>​
    

    Then, the following will work fine:

    .myblock1 div {
        display:block;
        background-color:#F00;
    }
    
    @media (min-width:600px) {
        #myblock2 {
            display:none;
        }
    }​