How to detect screen size and apply a CSS style

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.

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:

Download Detect screen size

If you liked this you might want to buy me a coffee :)

Spread the word, share this post
[del.icio.us] [Digg] [Facebook] [Google] [LinkedIn] [MySpace] [Reddit] [StumbleUpon] [Technorati] [Twitter] [Yahoo!] [Email]

Posted on Wednesday, August 19th, 2009 in .
RSS 2.0 feed for comments.

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

  1. How to detect screen size and apply a CSS style - Programming Blog

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

    August 23rd, 2009 at 12:12 am

  2. iwanna

    i love it!

    August 24th, 2009 at 11:09 am

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

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

    August 24th, 2009 at 5:41 pm

  4. Brad

    Very cool, thanks!

    August 24th, 2009 at 6:01 pm

  5. codingcereal

    very useful!

    August 25th, 2009 at 3:32 pm

  6. WPSMASH

    Thanks, I will use this in my new theme.

    August 28th, 2009 at 9:41 am

  7. Sergii

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

    August 31st, 2009 at 2:48 pm

  8. How to Detect Screen Size and apply a CSS Style | Choose Daily

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

    September 5th, 2009 at 1:05 pm

  9. Jorge Epuñan

    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/

    September 8th, 2009 at 1:30 pm

  10. Corinne

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

    September 12th, 2009 at 4:32 am

  11. Elliot

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

    September 13th, 2009 at 9:15 pm

  12. Luis

    Perfect! Thanks! Very useful tip! :)

    September 18th, 2009 at 10:12 pm

  13. aaln

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

    October 2nd, 2009 at 9:43 pm

  14. Jake

    Thanks, great tip!

    October 14th, 2009 at 6:42 am

  15. Nathan B.

    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!

    October 26th, 2009 at 3:50 pm

  16. Elliot

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

    October 26th, 2009 at 5:12 pm

  17. wptidbits

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

    November 24th, 2009 at 10:21 am

  18. Elliot

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

    November 25th, 2009 at 5:55 pm

  19. T.James

    amazing tip, thanks!!!

    p.s. this website is so beautiful :)

    November 30th, 2009 at 3:46 am

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

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

    December 19th, 2009 at 6:13 pm

  21. Frederick

    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!

    January 6th, 2010 at 2:24 am

  22. Jennilyn Lolo

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

    January 29th, 2010 at 5:58 am

  23. Elio

    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?

    January 29th, 2010 at 11:48 am

  24. Elio

    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

    February 1st, 2010 at 8:28 pm

  25. Mike

    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

    March 8th, 2010 at 6:53 am

Leave a comment