وبسایت آموزش برنامه نویسی

CSS Media Queries on @import Rules

CSS Media Queries on @import Rules

This page applies CSS Media Queries to an @import rule. It’s designed to show how you can conditionally import a stylesheet based, in this case, on viewport width. Desktop browsers ignore any viewport declaration so that the viewport is whatever the actual width of the browser window is — and that’s something you can easily change to see how this works.

The stylehseet names are self explanatory, the key thing is the way that the 3 different stylesheets are called which is:

@import url(red.css) (min-width:400px);
@import url(green.css) (min-width:600px);
@import url(blue.css) (min-width:800px);
If you’re on a desktop, just re-size your browser to see the effect. If you’re using an old version of Internet Explorer, this won’t work – you’ll just see a page without any styling at all. I have not included a workaround for this demo.

I have not, but could have, included other parameters, such as max-width, so, I might have

@import url(red.css) (min-width:400px) and (max-width:599px);

I haven’t done so because I want to use Ethan Marcotte’s Responsive Web Design ideas where each stylesheet just builds on the previous one(s). Including a max width would “switch off” a stylesheet beyond a certain width, creating a separate design rather than simply making one single design that adapts. You can see this even in this simple example.

Up until 400px wide, no styles are applied. That usually means you’ll see a black serif font on a white background. The red.css file sets the background colour to red, the foreground colour to white and the font family to sans-serif. I don’t need to repeat the foreground colour definition or the font family definition as the screen gets bigger. The font on the widest screen is a sans-serif because it’s still applying the red.css styles – I’ve just overridden the background colour.

For chapter and verse on this, see the Media Queries specification (currently at Candidate Recommendation).