Have you wanted to use a different CSS style sheet (design) based on your visitors screen resolution? One of our visitors asked this question and I knew it could be done, but didn't remember how. I have seen several scripts on the internet, but when I checked, most of them did not work right. I searched and found one at tek-tips.com (a great technical help forum). This one looked promising, but it too produced an error when I tried it. I went to the appropriate forum and received some great help. Thanks to some of their members, I found a solution.
Here is my test scenario. I want to display one CSS layout for most visitors (screen resolution 1024 wide and above) and a different layout for visitors still using 800 pixel wide screens (about 29% of users - as of this writing). By using a JavaScript to detect their screen resolution and switch the external CSS style sheet, we can accomplish this.
In my example below, the colored <div> box will change background and text color based on your screen resolution. You have to change your settings to view this test. I am still working on one that will switch based on resizing your browser window. If you have one, please let me know and I will post it in the CSS Tips and Tricks section (and give you a credit link).
This is what you see at 1024 screen size and above - White text on a red background.
At less than 1024, you get yellow text on a blue background.
Change your screen resolution and see it change!
HTML Code (stripped for clarity):
<HTML lang=en>
<HEAD>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
<!--
function switchCSS() {
if (window.screen.availWidth < 1024) {
var myLink = document.getElementsByTagName('link')[0];
if (myLink) myLink.setAttribute('href', 'style800.css',
0);
}
}
//-->
</script>
</HEAD>
<body onload="switchCSS();">
<div id="test"><p>This is what you see at 1024 screen size and above - White
text
on a red background.</p>
<p>At less than 1024, you get yellow text on a blue
background.</p>
<p>Change your screen resolution and see it change!</p></div>
</body>
</HTML>
CSS Code (style.css - main style sheet):
#test {
width: 200px;
height: 200px;
border: 2px solid black;
background-color: red;
font-size: 125%;
color: white;
padding: 10px;
text-align: center;
font-weight: 900;
}
CSS Code (style800.css - switched style sheet)
#test {
width: 200px;
height: 200px;
border: 2px solid black;
background-color: blue;
font-size: 125%;
color: rgb(255,255,0); /*yellow rgb value*/
padding: 10px;
text-align: center;
font-weight: 900;
}
Notes: