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:
[...] 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!
Hmm demo doesn’t seem to be working for me when I resize the window to a smaller size. It seems to just keep alerting me with the larger screen size message. Having the same issue on a website I’m testing it on… any ideas?
Hi James, please note that this is for SCREEN SIZE instead of window size. It works by detecting your screen resolution, not your browser window. Change your screen resolution to something below 1024×768 (for the demo) and you will see how it detects it.
Actually when I resize the window and refresh the text displays as blue for a split second before going red again.
Thanks!
The text displays as blue while the alert dialog is being displayed, so you can see that it is changed if the screen resolution is 1024 or more. If it was 800×600 the text would remain blue.
Thanks for the reply Eilo, but if you look at this screen grab you’ll see what I mean – it’s changing to blue for a split second when the wrong alert pops up and then goes back to red:
http://www.zoost.ie/800×600-1.jpg
Indeed James, that’s the intended behaviour:
1) we load a default stylesheet. For this example, that stylesheet has a blue text style.
2) if the screen is larger than 800×600, we load a stylesheet to override the previous. That stylesheet overrides the default blue text with red text.
If you remove the alert() call in the JS, you will see how this stylesheet replacement in instantaneous and you can’t see any blue text. That’s why I added the alert() call so it would pause the script so that we could have a glimpse at the old stylesheet being replaced.
Thanx for code dear m use than review.
hi great just what i am looking for. although i dont wish to so an alert box i just want it to detect and change the style sheet. if i remove the alert will it work as i want?
Yes Darren, it will work. the alert is just for feedback, so feel free to remove it.
hi! congrats for this post!
i made it play although i changed the :not(:first) but i cannot understand something. We read here http://api.jquery.com/attr/ that “It’s important to note that the .attr() method gets the attribute value for only the first element in the matched set.” However i have to choose between three .css styles according to three cases of screen.witdh. The problem is that it is playing! but it shouldn’t! Changing tha 1st .css style the third one should override the others and it should play that one (the last). When i put :last it plays again correctly (i understand why). when i put :first it doesn’t play the propriate .css (i understand why). But why to play correctly when i put nothing of :not, :first, :last etc.? it was supposed to replace the first .css and not the last nor all of them. please can you explain me?? Note: i only have three .ccs styles and i want only one to play! they all have the same divs and classes. the values are the only changes.
thanx in advance!
The same thing I was searching for, My problem was to set the background property based on the screen size i.e. load the small background for small screen and bigone for big resolution screens.
Thanks.
how to apply multiple css (files)using this article pls help me.
its seems to work intill i remove this line
This is part of the article How to detect screen size and apply a CSS style.
why does that brek everything?
Maybe there’s some other stuff in your code doing some strange thing. I’ve just tested it removing the line you mentioned and it’s working.
The code doesn’t affect to the DOM in anyway: it just loads one stylesheet or the other depending on the screen size(the monitor screen that is, not the browser window).
wowwwwww….thankyou verymuch…………luv u……
Thanks a lot!!
wow, this is a simple and brilliant script…. thanks a lot.
Nice script.
how can I have 2 or 3 css files on the page?
It seems that the script only works with one css file for each screen size.
Thanks
I can’t get this to work correctly.
On a 1920×1200 resolution screen the detect.js script says it has detected it as 1920×1200 but it ends up using the wrong css file.
here is my code:
<script
$(document).ready(function() {
if ((screen.width>=1920) && (screen.height>=1200))
{
alert(‘Screen size: 1920×1200 or larger’);
$(“link[rel=stylesheet]:not(:first)”).attr({href : “detect1920_1200.css”});
}
else
{
alert(‘Screen size: less than 1920×1200, 800×600 maybe?’);
$(“link[rel=stylesheet]:not(:first)”).attr({href : “detect1280_800.css”});
}
});
If you’re using jQuery 1.6.1 try using prop instead of attr and adding quotes to selectors using values. These were only some of the things that were changed on jQuery 1.6.
I”m using the JQuery file from this website.
It seems like the stylesheet links in the html are taking over depending on what is listed first.
Certainly, Kevin. The first stylesheet applies the initial styles, while the second one applies styles that, depending on the screen size, overrides the first styles.
Hi,
I just used your script. This is good! But I have a question, if I resize my browser to 1024×768 on my laptop 1024×768 resolution, I get the same message that says to me that I’m using a screen larger then 1024..
I work with a 1920×1080 screen on my laptop.
Can you help me?
Even on your exemple, on my laptop, I get the “Screen larger then …” even if I’m on 1024.
You could try checking what’s the screen width by adding the following before the if sentence:
alert('width:' + screen.width);You will see there what’s the screen size detected by the browser’s DOM.
In addition, you could remove the height checking in the if sentence so it will only check the screen width.
Hey, this is definitely a great screen for detecting screen size. Thanks a lot!!!
Want to ask if I want to detect three screen size in particular; say 800x600px; 1024X768px; and 1440X900px; what shall i change in the js?
Thanks for help
Eunice, you could use the switch-case-break conditional structure to test for many different screen sizes and load the proper stylesheet.
All is working perfectly in firefox and safari, but opening in ie8 makes it crash completely.
Is this common? Any help would be great!
if your current screen size has
width>=1024 and height>=768, browser will load only 1 css files is “detect1024.css” >> That’s good.
But if your screen size is < 1024 Then browser have to download 2 css files (detect1024.css and detect800.css), you can check it in the Net/css panel of firebug.
another way is use CSS3
ex:
<head>
<title>CSS3 Screen size </title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<link rel=”stylesheet” media=”only screen and (max-width: 1024px)” href=”detect800.css” />
<link rel=”stylesheet” media=”only screen and (min-width: 1024px)” href=”detect1024.css” />
</head>
Can someone please help me. I have tried to use this on a site but I cannot get it to work….. The site has been designed to fit a 1280 x 960 so I am really trying to just size it down for smaller screens. I have images and on the page and I tried to get help before but I weas told the images were too big, too wide and too heavy for the web so, “the page is going to stretch out to the size if the widest image and cut everything off because the page size cannot be smaller than the narrowest image, no matter how small the window size gets.” I am confused….. Is there no way that this will work for my site then? Can anyone help me please?
I pasted the Javascript inside my .
I get the alert if the screen size is bigger than 800×600 and smaller than 1024x….
it won’t load the css file. I tried also href=”css/detect800.css”
thank you
I know this is for screen resolution detection, not actual window size, but is there a way to do this for window size?
Here’s the experience I’m looking for: A user views a page at 1280 x 960 resolution, but their current window size for the browser is 600 x 600. In this case, they get 600.css. But if they drag the corner of the window and make it larger, it switches to using 600_plus.css.
David, your case would be better served using css media queries, but if for some reason you don’t want to use them (for example, browser compatibility), you should change the code and write a listener that detects the window resizing, probably using the resize jQuery method.