Sometimes we need to format the content differently according to the screen resolution of the user. One of the ways to do this is to simply detect the screen width using the screen.width property and change the stylesheet. In this tutorial we’re going to see how to do that using jQuery.
Before we begin, that a look at what we will be building
Detecting screen size with jQuery demo
The first step is to load our base stylesheets, the jQuery library and our javascript.
<link rel="stylesheet" type="text/css" href="reset.css"/> <link rel="stylesheet" type="text/css" href="detect800.css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="detect.js"></script> </head> <body> <div>The colour of this text will change.</div> </body>
We’re going to test if the user screen size is less than 1024 x 768 and if it is, we’ll change the stylesheet.
Define the same style in two different sheets. Once for the 1024 x 768 and once for the 800 x 600. Just make something quick and distinctive, for detect800.css I’m adding
div{
color: #006699;
font: 24px Georgia, serif;
}
and for detect1024.css:
div{
color: #df0000;
font: 24px "Trebuchet MS", sans-serif;
}
We’re going to add a JavaScript alert so the execution will pause until we click OK and we get to see the former style.
$(document).ready(function() {
if ((screen.width>=1024) && (screen.height>=768)) {
alert('Screen size: 1024x768 or larger');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"});
}
else {
alert('Screen size: less than 1024x768, 800x600 maybe?');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"});
}
});
As a selector, we look for the link element with a rel attribute with a value of stylesheet. We’re going to redirect its href to a different stylesheet. Now, since I’m loading a reset stylesheet in the first place, i will add the :not(:first) modifier, so it won’t affect the first element.
That’s it. Check the example of detecting screen width or just download the source files:
Posted on Wednesday, August 19th, 2009 in .
[...] DIRECT LINK » [...]
i love it!
[...] How to detect screen size and apply a CSS style [...]
Very cool, thanks!
very useful!
Thanks, I will use this in my new theme.
This is exactly what i’ve looking for. Thank you!
[...] How to Detect Screen Size and apply a CSS Style Detect Screen Size and apply CSS [...]
I wrote a plugin that makes the same thing, but it injects a class in intervals of width; it is documented in english and spanish:
http://www.csslab.cl/2009/07/22/jquery-browsersizr/
Thanks so much for this! I’ll have to give it a try for my own site.
You’re welcome, let me know how is it going
Perfect! Thanks! Very useful tip!
Great and useful tip!
I had to modify it for one of my client’s Drupal-based site since your code, as-is, will pretty much cancel all other css rules (Drupal will load a gazillion stylesheets.) After much googling, here’s the adapted version (compliments of Javascriptkit):
$(document).ready(function() {
if ((screen.width<=1024)) {
filename="sites/all/themes/mytheme/1024.css"
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
document.getElementsByTagName("head")[0].appendChild(fileref)
}
});
Thanks, great tip!
Love it, thanks! Is there an easy way to let the user override it and select the 1024-wide layout from a 800-wide screen? I noticed GoDaddy.com does this (“You are viewing the narrow version of our site; click here to view the full version ..”), but I don’t know how. Thanks!
Hi Nathan, I will take a look at it later and will see what I can do. I’m sure it can be replicated
Still it is using jquery, an advance version of javascript library. Anyway, it is very useful post. Gonna try it sometime. Thank!
wptidbits, jQuery is a library but JavaScript is not a library, JavaScript is the full language.
amazing tip, thanks!!!
p.s. this website is so beautiful
[...] How to detect screen size and apply a CSS style [...]
What if I want to detect the mobile phone’s screen size and then create a css stylesheet with a width = mobile screen size? Do you have a sample script for this situation? Really need your help. Thanks!
Is there any other way to capture the screen size without using jquery?
Jennilyn, you must capture the client screen size using a client-side script. You could write a script in vanilla JavaScript but why would you want to do it?
Frederick, you could try using this in your stylesheet:
@media all and (max-width: 480px) {
#content { font-family:Tahoma;
}
}
this would target iPhone screen, whose resolution is 480×320
jQuery.event.add(window, “load”, resizeFrame);
jQuery.event.add(window, “resize”, resizeFrame);
function resizeFrame()
{
var w = $(window).width();
$(“#content”).css(‘width’, w – 180 );
}
Resize content for Joomla! CMS Cool thx!
Mike
Bluestratus.com
Great for moving social buttons accordingly like mashable.
Problem with this is that a user can alter the size of their browser window and the window size can change based on toolbar apps etc. screen.width and screen.height have been around a long long time but generally are unacceptable to use due to the reasons I noted.
Instead, what one does is use good CSS design to make sure your CSS template adapts automatically to screen width so you never use fixed widths, always percentiles. You never use “PX” or Point font sizes, you use EM units.
Nice! Hopefully though CSS3 media conditions will replace the js method. (If IE decides to catch up)
[...] http://www.ilovecolors.com.ar/detect-screen-size-css-style/ #avg_ls_inline_popup { position:absolute; z-index:9999; padding: 0px 0px; margin-left: 0px; margin-top: 0px; width: 240px; overflow: hidden; word-wrap: break-word; color: black; font-size: 10px; text-align: left; line-height: 13px;} [...]
[...] How to detect screen size and apply a CSS style | jQuery | ilovecolors I needed today to format the content differently according to the screen resolution of the user. So I thought that just by detecting the screen width using the screen.width property, I could change the stylesheet using jQuery. And so it was. Check the example and continue reading. [...]
Hi!
It doesn’t work in IE, tried in 6,7 and 8!
Anyone else had that problem?
Sanjin, it does work on all IE. Perhaps you’re testing it locally and getting the security golden bar. That’s why you’re trying to load a JS from your hard drive, which is something that scares IE a bit.
Check again the example and see that everything is working fine (I’ve just tested it again).
Hi, thank for the fast answer.
I just found the problem, I am using 2 screens (Extended), worked fine in Firefox, Safari, Chrome and Opera. But well IE is a bit special as always. So I just changed the resolution on my main screen and it worked! Didn’t think of that because it worked on the other browsers.
Thank you for some great tutorials
nice info gan !
it’s usefull !!
This is really very cool website. and thank you so much for such a nice tutorial.
thanks Savita, remember you can always subscribe to receive the latest news!