ARTICLE

Media Only Queries in CSS3

Posted by Abhimanyu K Vatsa Articles | JavaScript September 11, 2012
CSS3 has added media queries functionality to media="screen" that was added to CSS2. This article explores the media queries functionality.
Reader Level:

If you remember, CSS2 added support for the media="screen" way of defining which stylesheet to use for which representation of the data.

 

Now CSS3 has added a new feature to this functionality, by adding media queries. Basically, this means you can change stylesheets or styles on the web page based on for instance the width and height of the viewport/browser.

 

Today I tried my hand at getting around with this new feature and wrote this article about it. To explore this new feature follow the steps.
 

Step 1
 

Create a new style sheet file and use the following style definitions:
 

body {

        background-color:black;

    }
 

@media only screen and (max-width900px) {

    body {

        background-color:blue;

    }

}
 

@media only screen and (max-width600px) {

    body {

        background-color:white;

    }

}

 

To understand the above style rules which are pretty new to us, look at the body's "white" background-color (bottom one), it is relevant in the action when your viewport/browser's width is under the range 0px to 600px.
 

And in the same manner, the body's "blue" background-color (middle one) is relevant in the action when the viewport/browser's width is in the range 601px to 900px.

 

And the body's "black" background-color (top one) is relevant in the action when the viewport/browser's size crosses both rules.
 

In other words you can say, "@media only screen and ( * ) { * }" overrides all the existing style rules.
 

Step 2
 

Now to test above the rules, let's create the web page, place a style file reference on it and then run the page in the browser. And try to resize the browser window to see it in action.
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <link href="StyleSheet1.css" rel="stylesheet" />

</head>

<body>

    <form id="form1" runat="server">

    <div>

        Media Only Queries in CSS3 by Abhimanyu.

    </div>

    </form>

</body>

</html>
 

 

I hope you like it. Thanks.

COMMENT USING
Employers - Post Free Jobs