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:

Posted on Wednesday, August 19th, 2009 in .

“How to detect screen size and apply a CSS style” received 36 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!

Leave a comment