Otherwise known as “resolution dependent layouts”. Single website, different CSS files for rearranging a website to take advantage of the size available.
There is a W3C standard way of declaring them. One way is to test the “device-width”, like this:
<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />
The above code will apply the 800.css styling to the document only if the device viewing it has a width of 800px or wider. And… supports “media queries” in this way.
Keep in mind this is the device width, not the current width of the browser window. On the iPhone (3G(s)), that means 480px. My fancy new MacBook Pro is going to return 1920px for the device width. But my actual browser window is only half of that at this exact moment. The device width is quite useful when dealing with mobile devices where the browser is probably 100% of the screen whenever in use, but less useful in laptop/desktop browsers.
Seems to me far more useful is the current width of the browser window (“viewport”). We can even specify stylesheets that are only to be used when the viewport is between two different pixel sizes:
<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />
That stylesheet will only take affect when the current browser window is between 701 and 900 pixels in width.
Browser Support
IE 9+, Firefox 3.6+, Safari 3+, Any Chrome, Opera 10+. Mozilla suggests starting the media attribute of the <link /> with “only” which will hide the stylesheet from older browsers that don’t support media queries. That may or may not be what you actually want to do… case dependent of course.
<link rel="stylesheet" media="only screen and (color)" href="example.css" />
Generally, layout is one of those things that it’s tough to sell “progressive enhancement” on. Rounded corners becoming squares, no big deal. Messed up layout, that is a big deal. Devices like the iPhone right now are kind of great, since browser choice is so limited (there used to be just Mobile Safari and that’s it, now there is Opera as well) and they are very good browsers, you can rely on techniques like this to work.
If IE support is paramount, we always have JavaScript!
Doing it with jQuery
Using JavaScript, we can test the windows width and change the active CSS file accordingly. This will work across all browsers. You can have an ID for a <link /> element like any other, so let’s add that:
<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />
Then we can use that as a hook and change the href value of the stylesheet. The browser will see that change and unapply the old CSS and reapply the newly linked CSS. We’ll run our little adjustment test once right away, and then anytime the window is resized thereafter.
function adjustStyle(width) {
width = parseInt(width);
if (width < 701) {
$("#size-stylesheet").attr("href", "css/narrow.css");
} else if (width < 900) {
$("#size-stylesheet").attr("href", "css/medium.css");
} else {
$("#size-stylesheet").attr("href", "css/wide.css");
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
Is jQuery really necessary just for this?
No, but I’m sure you know that’s just how I roll in general and it makes it easier. Kevin Hale wrote about dynamic resolution layouts literally five years ago. It’s “raw” JavaScript and still works great today.
Also, there is a kick ass polyfill: Respond.js
Video
Resolution Dependent Layout with CSS from Chris Coyier on Vimeo.
Example One
This one has a special stylesheet for narrow (less than 700px), medium (701 – 900px), and wide (greater than 901px) browser windows.
Example Two
This does the exact same thing as example one, only through jQuery/JavaScript instead of CSS media queries.
Example Three
This example shows that we can target mobile devices by testing for a maximum device width.
Download
Snag all of these for reference in one place.
This is awesome. Many thx.
Looking to the future, will web designers have start making sites that are some the biggest & smallest to accomodate? Ask that question. :-P
Nice! Thanks for this Chris :)
Great tip! I’m going to give this a try. Thanks!
Very cool! Reminds me of http://lessframework.com/
interesting note: DreamweaverCS5 in all it’s wysiwyg glory supports this functionality….not the jquery bit, though. I saw a video of it when I was geeking out on all the cs5 previews.
Great article! Thanks for the walk-through.
ITS OVER NINE HUNDREEEDDD!!!
lol, had to.
fail
Wow, this is just great!
Lovely… what aboute Opera?
What about it?
I think Dim wants to know about support for this in Opera.
Daniel Got it.
No, I think Chris got it.
bu-dum tsss
I just mean I specifically covered it in the article and mini screencast. It works =)
Wow, this comes in handy! Thanks!
Awesome! I was looking for this.
Awesome idea and awesome examples Chris, but as much I like it, it also scares me. In the wrong hands, will the power be used for good or evil?
Great article..
Thanks chris..
Great job. Love the workaround for IE. (Even though I don’t use it)
I wrote a jQuery plugin for this, so it is interoperable between browsers (even the IE family): jQuery browserSizr.
http://www.csslab.cl/2009/07/22/jquery-browsersizr/
Great article thanks.
You don’t need JavaScript to build fluid layouts. Sure, it’s cool to display additional content, but if you don’t have it there initially, you might as well just stick to what you have. Make all your site fluid and you have this effect too.
This is not a strict fluid layout though. It is a completely different layout depending on the window width.
A true fluid layout would just scale widths measured in percent.
Nice one, thanks!
Btw, what is the name of the iphone simulator?
iPhone simulator
with a capitalized P.
I am loving the alternate CSS sheets with max width. That takes care of a lot of things I am working on for Mobile devices without using jQuery if the browser does not have javascript support.
I actually like to use both the ‘width’ and ‘device-width’ Media Queries when designing for mobile devices.
Why not cover both eventualities :)
I’ve put the implementation details here,
http://protofluid.com/?c=mediaQueries
Does the max device width work on IE browser devices? Blackberries, Androids, I know iPhones for sure.
Or is javascript the way to go on those. I hate developing for IE or any device using IE but it must be done. I don’t think many IE mobile devices even have Javascript enabled on their browsers. Don’t know about the Mobile7 MS devices.
Very cool article.
thanks in advace.
Would this work with @media?
Ex.
@media screen and (min-width: 490px) and (max-width: 1600px) {
}
Yes, that is how I like doing it!
You have many options for specifying Media Queries, but I have to admit, this seems neatest to me.
This is AWESOME!!! Thank you sooo very much for sharing. I could have used this a long time ago. : )
I would like to see a liquid-layout version of this where each of the three layouts stretched to fill the full width of the browser viewport. Then it would truly be a resolution independent layout.
Nice article Chris.
I tried the media=”only screen and (color)” with IE 9 Platform Preview and it doesn’t support it so far.
Interesting article, Chris. I think it would be cool to use this to increase the main-content area’s width for people with larger screens.
Just a FYI: You call it Vanilla, not “raw” JavaScript.
Can we call it “bareback” JavaScript?
Can I call it sweetheart?
Great tip. This probably is more dificult to implement but it gives me that warm felling that it’s the right way to do it. Designing sites that run anywhere beautifully. :)
Any thoughts about the best way to implement this on a layout with images? Probably it would envolve using some of the techniques described by robot ninja at http://unstoppablerobotninja.com/entry/fluid-images/
Great info !!! Thanks for sharing Chris
I knew how to do this with javascript but not “device-width” thing. It is very cool~
Very nice, I was just looking for a clean way to target mobile devices.
One thing though: the second example doesn’t work right in Chrome on Windows; the Content and Extra div’s aren’t aligned properly. Is this because of the demoing or is this something with the JS? (as far as I can see it uses the same stylesheet).
cool for designers/developers. but, will readers find shifting/moving content useful?
Why would they like constantly changing window size?
wow! thanks!
Was working on something like this . it helped
Ok that’s awsome! Endless possibilities.
You kinda cut it short to the end, what happened? :)
After reading this it has made me really think whether I should start designing sites so that they are iPhone etc friendly.
I look at the sites have done in iPhones and other portable media devices, and they look fine, only issue is scrolling sideways etc. But I guess the future seems to be heading towards small screen devices and therefore sites should cater for the growing market.
I have read somewhere that dreamweaver CS5 will have some kind of functionality that allows you to create a site then dreamweaver will create stylesheets automatically for devices such as iPhones etc.
This and more can be done easily with Elastic CSS Framework, check out Adaptive Columns in the Demo Section.
Pretty neat, I didn’t know such thing was possible with pure css–of course IE has to come and ruin it as usual, but thanks for the jQ example too. I wonder you could post a MooTools example too, or maybe this is something to poke David Walsh about xD
I see this feature in Nettut+ blog and would like to make some script to do this. But you’ve already done all of this, even better with only css. Thank you for sharing.
I totally agree for this method, particularly for development of different stylesheets for various mobile devices.
Check out ProtoFluid which takes advantage of this technique (we very recently launched it!). http://protofluid.com
It lets you test CSS3 Media Queries at specified resolutions (i.e. mobile phone widths) with great ease.
Thanks for the article, great timing ;)
Thanks for useful article. best regards man
This is nice article….i have come to know first time about define different CSS in header to control layout as per devices.
I was in habit of using single CSS with 100% width define and when i use %, it automatic adjust as per the browser width.
Jquery is good and will try that also
Idea pioneered by The Man In Blue: http://themaninblue.com/writing/perspective/2004/09/21/
hi,
This will be really nice if this will supoort for IE!
However great technique and thankx for sharing.
Excellent article. Thanks Ted
Maybe you’ll like the auto-resize features of our little jQuery experiment: http://centratissimo.musings.it
Take a look and let us know if you like it!
Article comes up on the 23rd, need for exactly this comes up on the 27th. You just saved me from a huge headache. Thankyou!
Really nice article Chris! This could be a nifty trick to support all phones out there. But I’m abit suspicious about it. I mean they dont support jQuerry right?
A great concept, but I do not feel as though its plausible. Shifting content dependent upon browser width could be exceptionally dangerous. Users do not like when things start shifting about randomly. They have this tendency to think, “What’s going on with this site? Its obviously broken. I’ll go somewhere else.”
The utilization of device width however, especially for mobile devices, I think is much more useful. Unless you have an already well established web presence or a very tech savvy user base however, I would stay away from the media width.
Great Man! Awesome ………………………..
Nice Idea, but I think it don’t work in practice. The reason is for example, images have to be resized for different sizes. If you use it for a mobile design, you maybee load content which isn’t displayed in the end.
I guess this could also be used to, for example, switch layouts when viewing on an iPhone and changing the rotation (portrait/landscape) :)
Ive been looking for a post on this for ages… My friend said you could have different style sheets in a W3C standard way and here it is. Cheers for the resource much appreciated.
I want to seel some popular site will adapt @media via css.
Nettuts+ — only real site I know that using technique, — with javascript.
I used @media query on some random small project, because was bored (and also to try it out).
Hi,
I have big problem
i using width 1180px for layout
in stylesheet i put container width 1180px;
in desktop pc my layout no problem but
is it possible to have one main css file, which includes the stylesheets for the relevant resolutions, instead of 3 link tags in the html?
greatings and thanks for the tip
Seriously? 50KB+ of modularized-to-hell, slow JavaScript just to change a stylesheet? The “raw” solution, or real solution as I call it, is about 2KB and doesn’t use 20,000 functions and 20,000 objects to grab an element.
None of this works. Waste of time…
Thanks, this is very very helpful. Is there a way to create the dynamic dropdown using the jquery method if the original menu has some css dropdown such as:
as you can see there is a second < ul > in the menu.
Oh great! I was thinking that I might need too much scripting for that. But this is not the case. thanks for great tutorial. Now my website is pretty much compatible with mobile devices.
what an awesome article. super easy fix for making a great fluid layout. thanks bro!
WOW thanks alot
This was really great learning. A difference between max-width and max-device width. This is the trick here everyone should learn.
My main concern is: Will the different linked stylesheets be loaded EVEN if they are out of range for the current device?
In otherwords, are the linked stylesheets “selected” or “loaded” by device width?
I’d like them not to be even loaded at all if the current device is outside the specified limits, or if the device or your html have the landscape option disabled (I don’t konw how it’s called when you rotate the device).
I tried to write this out and when i tested it nothing happened. I used both the jquery and css media method (together and separately). My main goal is for mainly browser window resizes.