Posted By

paulgrenwood on 09/23/09


Tagged

css screensize


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

aleksanderek
robotici


Detect Screen Size & Apply CSS


 / Published in: CSS
 

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.

  1. // The first step is to load our base stylesheets, the jQuery library and our javascript.
  2.  
  3. <link rel="stylesheet" type="text/css" href="reset.css"/>
  4. <link rel="stylesheet" type="text/css" href="detect800.css"/>
  5. <script type="text/javascript" src="jquery.js"></script>
  6. <script type="text/javascript" src="detect.js"></script>
  7. </head>
  8. <body>
  9. <div>The colour of this text will change.</div>
  10. </body>
  11.  
  12.  
  13. // 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.
  14. //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
  15.  
  16. div{
  17. color: #006699;
  18. font: 24px Georgia, serif;
  19. }
  20.  
  21.  
  22. // and for detect1024.css:
  23.  
  24. div{
  25. color: #df0000;
  26. font: 24px "Trebuchet MS", sans-serif;
  27. }
  28.  
  29.  
  30. // 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.
  31.  
  32. $(document).ready(function() {
  33.  
  34. if ((screen.width>=1024) && (screen.height>=768)) {
  35. alert('Screen size: 1024x768 or larger');
  36. $("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"});
  37. }
  38. else {
  39. alert('Screen size: less than 1024x768, 800x600 maybe?');
  40. $("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"});
  41. }
  42. });
  43.  
  44.  
  45. // 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.

Report this snippet  

You need to login to post a comment.