Allground - Responsive Fullscreen Backgrounds for WordPress with images, YouTube videos, Google Maps and self hosted videos

How to detect screen size and apply a CSS style

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

Loading…

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.

The changing style

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;
}

Detecting screen width

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:


“How to detect screen size and apply a CSS style” received 75 comments! Add yours.

  1. How to detect screen size and apply a CSS style - Programming Blog August 23rd, 2009

    [...] DIRECT LINK » [...]

  2. iwanna August 24th, 2009

    i love it!

  3. Favourite links for August 24, 2009 | Crescent Gfx August 24th, 2009

    [...] How to detect screen size and apply a CSS style [...]

  4. Brad August 24th, 2009

    Very cool, thanks!

  5. codingcereal August 25th, 2009

    very useful!

  6. WPSMASH August 28th, 2009

    Thanks, I will use this in my new theme.

  7. Sergii August 31st, 2009

    This is exactly what i’ve looking for. Thank you!

  8. How to Detect Screen Size and apply a CSS Style | Choose Daily September 5th, 2009

    [...] How to Detect Screen Size and apply a CSS Style Detect Screen Size and apply CSS [...]

  9. Jorge Epuñan September 8th, 2009

    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/

  10. Corinne September 12th, 2009

    Thanks so much for this! I’ll have to give it a try for my own site.

  11. Elliot September 13th, 2009

    You’re welcome, let me know how is it going :)

  12. Luis September 18th, 2009

    Perfect! Thanks! Very useful tip! :)

  13. aaln October 2nd, 2009

    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)
    }
    });

  14. Jake October 14th, 2009

    Thanks, great tip!

  15. Nathan B. October 26th, 2009

    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!

  16. Elliot October 26th, 2009

    Hi Nathan, I will take a look at it later and will see what I can do. I’m sure it can be replicated :)

  17. wptidbits November 24th, 2009

    Still it is using jquery, an advance version of javascript library. Anyway, it is very useful post. Gonna try it sometime. Thank!

  18. Elliot November 25th, 2009

    wptidbits, jQuery is a library but JavaScript is not a library, JavaScript is the full language.

  19. T.James November 30th, 2009

    amazing tip, thanks!!!

    p.s. this website is so beautiful :)

  20. Favourite links for August 24, 2009 | Violet Pear December 19th, 2009

    [...] How to detect screen size and apply a CSS style [...]

  21. Frederick January 6th, 2010

    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!

  22. Jennilyn Lolo January 29th, 2010

    Is there any other way to capture the screen size without using jquery?

  23. Elio January 29th, 2010

    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?

  24. Elio February 1st, 2010

    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

  25. Mike March 8th, 2010

    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

  26. Bob March 16th, 2010

    Great for moving social buttons accordingly like mashable.

  27. rg April 17th, 2010

    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.

  28. Tyler June 7th, 2010

    Nice! Hopefully though CSS3 media conditions will replace the js method. (If IE decides to catch up)

  29. Detect Screensize | The Brain Trust June 24th, 2010

    [...] 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;} [...]

  30. How to detect screen size and apply a CSS style with jQuery « Web Page Authority Blog July 14th, 2010

    [...] 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. [...]

  31. Sanjin July 21st, 2010

    Hi!

    It doesn’t work in IE, tried in 6,7 and 8! :(

    Anyone else had that problem?

  32. Elio July 21st, 2010

    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).

  33. Sanjin July 22nd, 2010

    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 :)

  34. Mas Irwan July 31st, 2010

    nice info gan !
    it’s usefull !!

  35. Savita August 2nd, 2010

    This is really very cool website. and thank you so much for such a nice tutorial.

  36. Elio August 2nd, 2010

    thanks Savita, remember you can always subscribe to receive the latest news!

  37. James R October 27th, 2010

    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?

  38. Elio October 27th, 2010

    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.

  39. James R October 27th, 2010

    Actually when I resize the window and refresh the text displays as blue for a split second before going red again.

    Thanks! :)

  40. Elio October 27th, 2010

    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.

  41. James R October 28th, 2010

    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

  42. Elio October 28th, 2010

    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.

  43. Ashwani Mehra November 13th, 2010

    Thanx for code dear m use than review.

  44. darren November 16th, 2010

    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?

  45. Elio November 16th, 2010

    Yes Darren, it will work. the alert is just for feedback, so feel free to remove it.

  46. kontopro December 18th, 2010

    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!

  47. Hiren Khambhayta December 20th, 2010

    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.

  48. balaji January 3rd, 2011

    how to apply multiple css (files)using this article pls help me.

  49. Conan January 29th, 2011

    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?

  50. Elio January 31st, 2011

    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).

  51. sarath krishna February 20th, 2011

    wowwwwww….thankyou verymuch…………luv u……

  52. biko ngari March 5th, 2011

    Thanks a lot!!

  53. Maverick April 12th, 2011

    wow, this is a simple and brilliant script…. thanks a lot.

  54. Jorge Sousa May 1st, 2011

    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

  55. Kevin B May 26th, 2011

    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”});
    }

    });

  56. Elio May 26th, 2011

    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.

  57. Kevin B May 26th, 2011

    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.

  58. Elio July 7th, 2011

    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.

  59. Patrice July 19th, 2011

    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.

  60. Elio July 19th, 2011

    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.

  61. Eunice July 21st, 2011

    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

  62. Elio July 21st, 2011

    Eunice, you could use the switch-case-break conditional structure to test for many different screen sizes and load the proper stylesheet.

  63. Andy August 28th, 2011

    All is working perfectly in firefox and safari, but opening in ie8 makes it crash completely.

    Is this common? Any help would be great!

  64. DD.Minh September 8th, 2011

    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.

  65. DD.Minh September 8th, 2011

    another way is use CSS3
    ex:

  66. DD.Minh September 8th, 2011

    <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>

  67. Michelle October 21st, 2011

    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?

  68. Hans November 2nd, 2011

    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”

  69. amit December 16th, 2011

    thank you

  70. David Ashleydale January 6th, 2012

    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.

  71. Elio January 9th, 2012

    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.

  72. Kayne February 9th, 2012

    you could change
    screen.width to document.body.clientWidth to get the window width instead of the screen :)

  73. » Bad Design is a Sin A Load of Old Blogposts February 11th, 2012

    [...] people with higher resolutions are forced to use the same CSS. For years now there have been many ways to detect screen resolution and serve different CSS based on screen real-estate. Would it be so hard [...]

  74. Daily Dump 20090923 | Blog .Ronald April 24th, 2013

    [...] How to detect screen size and apply a CSS style [...]

  75. Andy July 3rd, 2013

    Lazy? You couldn’t even be bothered to bring some positivity into your pointless reply by posting your 1 line of css. Asshole.

Leave a comment