Change CSS File in ASP.NET Web Application Based on Resolution of the Client Machine

To make your ASP.NET page render smartly based on the resolution of the client desktop you might want to change CSS file with different style defined in it for different resolutions. Below is the sample JavaScript code you can use for the same.

You can download the entire code sample from this link Sample - ASP.NET Dynamic CSS File Demo

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic CSS Demo</title>
 
    <script>
        //based on resolution change css on load
        var a = window.screen;
 
        var styleNode = document.createElement('link');
 
        styleNode.setAttribute('rel', 'stylesheet');
        styleNode.setAttribute('type', 'text/css');
         
        if (a.width == "800" & a.height == "600")
        {
            alert("Your system resolution is:800 * 600");
            styleNode.setAttribute('href', 'css/StyleSheet1.css');
        }
        else if (a.width == "1024" & a.height == "768")
        {
            alert("Your system resolution is: 1024*768");
            styleNode.setAttribute('href', 'css/StyleSheet2.css');
        }
        else if (a.width == "1360" & a.height == "768")
        {
            alert("Your system resolution is:1360*768");
            styleNode.setAttribute('href', 'css/StyleSheet3.css');
        }
 
        document.getElementsByTagName('head')[0].appendChild(styleNode);
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
        <p class="TextColor">This is Dynamic CSS demo. CSS will change based on the resolution of client system.</p>
 
        Green - Resolution 800*600 <br />
        Red - Resolution 1024*768 <br />
        Blue - Resolution 1360*768
    </div>
    </form>
</body>
</html>

See Also