ASP.NET : Dynamically change a style at Run-Time
Sep 21, 2009
A nice feature of CSS is the ability to assign multiple classes to can DOM element via the class attribute. This opens up the possibility to dynamically set a class assignment based on some logic as the page is being rendered.
The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.
This is a simple method to return a style rule to define the background color of the page. I have three rules defined.
The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.
<div class="contentBox bkg1">...</div>I find the solution from Chris blog, for easiest way to set something like a dynamic style at run-time is to define a public method in the page class to return the desired rule. For my demonstration I will return a style rule name based on a QueryString parameter, but you can use all sorts of criteria. I also chose to apply the rule to the Body tag.
This is a simple method to return a style rule to define the background color of the page. I have three rules defined.
public string GetBackgroundClass()The style rules just set the color as follows, a nice egg shell (at least that is what I call it), red and blue.
{
switch ( Request.QueryString["bkg"])
{
case "1":
return "bkg1";
case "2":
return "bkg2";
case "3":
return "bkg3";
default:
return "bkg1";
}
}
.bkg1Finally I just inline the call to the method in the HTML markup:
{
background-color: #FFFFCC;
}
.bkg2
{
background-color: #C30000;
}
.bkg3
{
background-color: #0000CC;
}
<body class="<%=GetBackgroundClass() %>">I hope this ll help you. A 'Thank You' would be nice!
Share