Media Only Queries in CSS3 / @media only screen and (max-width: 900px) { attributes; }

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 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 get around on this new feature and the same posting here. To explore this new feature follow the steps.

Step 1

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

body {
        background-color:black;
    }

@media only screen and (max-width: 900px) {
    body {
        background-color:blue;
    }
}

@media only screen and (max-width: 600px) {
    body {
        background-color:white;
    }
}

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

And the same, body’s ‘blue’ background-color (middle one) will come in action when viewport/browser’s width will fall under range 601px to 900px.

And body’s ‘black’ background-color (top one) will come in action when viewport/browser’s size crosses the both rules.

Means you can say, “@media only screen and ( * ) { * }” overrides the existing all style rules.

Step 2

Now to test above rules, let’s create the web page, place a style file reference on it and then run the page in 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.

Comments

  1. Hi,
    I am using VS2010 and IE8. Installed css3 from http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210

    wrote the stylesheet in css3, I am not getting any intellisense and above mentioned code is not working in my IE. Color always remain the same (Black). Please advise what is missing from my end.

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System