Haroldo
Haroldo

Reputation: 37377

conditional statement for screen resolution?

I would like to use a conditional statement to attach a different stylesheet for:

if the clients resolution is <= 1024*768

I'm pretty sure this is possible, but have never seen the code for it before?

ps. I am not looking for a javascript solution

Upvotes: 14

Views: 42672

Answers (3)

OG Sean
OG Sean

Reputation: 1065

Typically people don't "attach another stylesheet" for screen resolution because you could resize the browser after page load, changing the resolution, and you don't want file loading every time you do.

This will do the trick, in one CSS file or wherever you normally put your CSS...

Ex:

/* css as usual */
.this-class { font-size: 12px; }

/* condition for screen size minimum of 500px */
@media (min-width:500px) {

  /* your conditional / responsive CSS inside this condition */

  .this-class { font-size: 20px; }

}

This should change the font size to 20px when the @media query condition is true, in this case when the screen is over 500px.

As you size your browser up and down you will see the conditional CSS rules take effect automatically, no JS needed.

Upvotes: 28

frenchie
frenchie

Reputation: 52017

There's this option, totally client side and javascript driven, add a script tag:

<script type="text/javascript">

if (screen.height < 900) { 

document.write('<link href="UrLowRes.css" type="text/css" rel="stylesheet"/>');

} else { 

document.write('<link href="UrlHighRes.css" type="text/css" rel="stylesheet"/>');

} 

</script>

You could even add other if statements for smartphones and tablets.

Upvotes: 1

Quentin
Quentin

Reputation: 944197

CSS 3 introduces media queries, but it is new and support is not all that widespread yet (Firefox only introduced it in version 3.5, for instance, and Internet Explorer won't get it until version 9) so build with progressive enhancement in mind. CSS Tricks has a tutorial for providing different CSS for different browser window sizes (which is a more useful metric then display resolution).

You can test support for your browser.

Upvotes: 14

Related Questions