AndrewS
AndrewS

Reputation: 1565

Detect screen size with jQuery and apply a CSS style

I searched and found many examples on web, and even here in stackoverflow, but none of them is 100% explained. For those who wants to place a answer with CSS media screen, please don't do that I know about it. But this question is more for IE7+. since it doesn't support "CSS media screen".

This is the example i found:

$(document).ready(function() {

if (screen.width>=800) {
    $("link[rel=stylesheet]:not(:first)").attr({href : "style1.css"});
    } else {
    $("link[rel=stylesheet]:not(:first)").attr({href : "style.css"});
    }
});

I am new to jquery, so how to change this script in case if I have 4 different styles for 4 different screen resolutions.

So I would liek to have something like this:

  1. if screen > 1 && screen < 600
  2. if screen > 601 && screen < 1280
  3. if screen > 1281 && screen < 1600
  4. if screen > 1 1601

Please help me!

Upvotes: 2

Views: 7497

Answers (2)

Eli
Eli

Reputation: 14827

You don't need jQuery for this, using CSS3 media queries instead:

@media only screen and (max-width : 600px) {
   /* Styles for 1*/
}

@media only screen and (min-width : 601px) and (max-width : 1280px) {
   /* Styles for 2 */
}

@media only screen and (min-width : 1281px) and (max-width : 1600px) {
   /* Styles for 3 */
}

@media only screen and (min-width : 1601px) {
   /* Styles for 4 */
}

Ok, as @RaduChelariu mention, to support older browser like IE7 you can use a custom plugin to make CSS3 media queries compatible with.

Upvotes: 5

Radu Chelariu
Radu Chelariu

Reputation: 446

Actually, media queries are the answer. Just use this shiv to add media query support to IE7 and 8 and you're good to go. No need for messy javascript.

Upvotes: 1

Related Questions