Wednesday, July 9, 2008

Dynamic Stylesheet Assignment Dependent on Browser

I've two stylesheets. One for Internet Explorer & other for other browsers. When the client is IE, the web page should have IE-specific stylesheet attached. For rest of the browsers, the web page must use the other stylesheet.
Demo: Get two stylesheets with body background set to two different colors.
body
{
background-color:blue;
}
body
{
background-color:black;
}

Add the following code to Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
HtmlLink lnk = new HtmlLink();
if (Request.Browser.Type.Contains("IE"))
{
lnk.Href = "~/StyleSheet.css";
}
else
{
lnk.Href = "~/StyleSheet2.css";
}
lnk.Attributes.Add("rel", "stylesheet");
lnk.Attributes.Add("type", "text/css");
this.Header.Controls.Add(lnk);
}
Test with Internet Explorer & some other browser like Mozilla, Opera etc.