Search code examples
cssmedia-queries

CSS Media Type and Query is not working


I am having this CSS style, which i am trying to run on chrome v28, Firefox v222 and IE8:

html, body{
            margin: 36px;
            width: 100%;
            background-color: black;
        }

        @media screen and (max-width: 768px){
            html, body{
                width: 100%;
                height: 100%;
            }

            #page {
                margin: 20px;
                width: 100%;
                background-color: red;
            }
        }

and as a markup I add:

<!DOCTYPE html>
<html>
<head></head>
<body><div id="page"></div></body>
</html>  

Just want to understand why it is not changing color to red if I minimize the window.

Any Help will be great help.

Thanks Raja


Solution

  • #page has no content thus it has height:0px; Try the following: (working jsFiddle)

    @media screen and (max-width: 768px){
        html, body{
            width: 100%;
            height: 100%;
        }
    
        #page {
            margin: 20px;
            width: 100%;
            height:100%; /* set the height */
            background-color: red;
        }
    }
    

    As for the addition to the question - changing the background - You will have to reverse the order of the CSS like this:

    <style> 
    
    html, body{ 
        margin: 36px; width: 100%; height: 100%; 
    } 
    body{ background-color: black; } /* This should be first for the media query to override */
    
    @media screen and (max-width: 768px){ 
        html, body{ margin: 20x; } 
        body{ background-color: red; } /* When the media query is applied this overrides the previous rule */
    } 
    
    </style>