Style sheet from ASP.NET Code behind Based on Browser Type

Let's put browser detection and ASP.NET HTML classes in use to apply different style on the basis of browser type. In this example, we will see as how to detect user agent passed in request object and then create a style sheet reference dynamically based on browser type.

Final output:

Code:

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicStyleSheet.aspx.cs" Inherits="DynamicStyleSheet" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

 

</head>

<body>

<form id="form1" runat="server">

<div id="container">

<h1>Sample Div

</h1>

</div>

</form>

</body>

</html>

 

Code Behind:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

 

public partial class DynamicStyleSheet : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// HTML control of link type

HtmlLink stylesheetLink = new HtmlLink();

// Adding attributes based on std html link tag for stylesheet

// example output: <link type="text/css" rel="stylesheet" href="" />

stylesheetLink.Attributes.Add("type", "text/css");

stylesheetLink.Attributes.Add("rel", "stylesheet");

// Browser Detection for IE or Chrome

if (Request.Browser.Browser.Contains("IE"))

{

// Attaching stylesheet url to href attribute of link

stylesheetLink.Attributes.Add("href", ResolveClientUrl("~/styles/IEStyle.css"));

}

else if (Request.Browser.Browser.Contains("Chrome"))

{

stylesheetLink.Attributes.Add("href", ResolveClientUrl("~/styles/Chrome.css"));

}

// Adding control to Page's header section

Page.Header.Controls.Add(stylesheetLink);

}

}

 

Stylesheet for IE. Name: IEStyle.css

div#container

{

background-color:lightyellow;

width:200px;

height:200px;

border:1px dotted black;

}

 

Stylesheet for Chrome. Name: Chrome.css

div#container

{

background-color:lightGreen;

width:200px;

height:200px;

border:1px solid black;

}

Tags: , , , ,

ASP.NET