Adding css class through aspx code behind

CssClassasp.netCode Behind

Css Problem Overview


I am using aspx. If I have HTML as follows:

<div id="classMe"></div>

I am hoping to dynamically add a css class through the code behind file, ie on Page_Load. Is it possible?

Css Solutions


Solution 1 - Css

If you want to add attributes, including the class, you need to set runat="server" on the tag.

    <div id="classMe" runat="server"></div>

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")

Solution 2 - Css

If you're not using the id for anything other than code-behind reference (since .net mangles the ids), you could use a panel control and reference it in your codebehind:

<asp:panel runat="server" id="classMe"></asp:panel>

classMe.cssClass = "someClass"

Solution 3 - Css

Assuming your div has some CSS classes already...

<div id="classMe" CssClass="first"></div>

The following won't replace existing definitions:

ClassMe.CssClass += " second";

And if you are not sure until the very last moment...

string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";

Solution 4 - Css

controlName.CssClass="CSS Class Name";

working example follows below

txtBank.CssClass = "csError";

Solution 5 - Css

BtnAdd.CssClass = "BtnCss";

BtnCss should be present in your Css File.

(reference of that Css File name should be added to the aspx if needed)

Solution 6 - Css

Syntax:

controlName.CssClass="CSS Class Name";

Example:

txtBank.CssClass = "csError";

Solution 7 - Css

If you want to retain the existing class, this would work:

string existingClass = classMe.Attributes["class"];
classMe.CssClass = existingClass + " some-class";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanDanView Question on Stackoverflow
Solution 1 - CssChris HaasView Answer on Stackoverflow
Solution 2 - CssJasonView Answer on Stackoverflow
Solution 3 - CssMarc.2377View Answer on Stackoverflow
Solution 4 - CssAnwarView Answer on Stackoverflow
Solution 5 - CssVeerendranath DarsiView Answer on Stackoverflow
Solution 6 - CssKishor MakwanaView Answer on Stackoverflow
Solution 7 - CssJohn Oscar CervantesView Answer on Stackoverflow