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.

[html]

<link rel="stylesheet" type="text/css" href="reset.css"/>
<link rel="stylesheet" type="text/css" href="detect800.css"/>
http://jquery.js
http://detect.js
</head>
<body>
<div>The colour of this text will change.</div>
</body>

[/html]

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

[css]

div{
color: #006699;
font: 24px Georgia, serif;
}

[/css]

and for detect1024.css:

[css]

div{
color: #df0000;
font: 24px "Trebuchet MS", sans-serif;
}

[/css]

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.

[js]

$(document).ready(function() {

if ((screen.width>=1024) && (screen.height>=768)) {
alert(‘Screen size: 1024×768 or larger’);
$("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"});
}
else  {
alert(‘Screen size: less than 1024×768, 800×600 maybe?’);
$("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"});
}
});

[/js]

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:

75 thoughts on “How to detect screen size and apply a CSS style”

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

  2. 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!

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

  3. 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!

    1. 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?

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

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

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

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

  8. 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 🙂

  9. 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?

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

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

    Thanks! 🙂

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

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

  13. 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?

  14. 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!

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

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

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

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

    });

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

Leave a Reply