G.T.D.
G.T.D.

Reputation: 396

Modify an HTML tag level CSS selector from the code behind

I want to be able to fully manipulate all CSS selectors (including classes and semantic tags) using the ASP.NET backend code. Like so:

CSS:

html {
    color: black;
}

.myClass {
    width: 100px;
}

Desired C#:

protected void Page_Load(...) {
    // Some code & if logic ...
    html.Attributes.Add("style", "color: green")
    myClass.Attributes.Add("style", "width: 325px")
}

However, the C# aspect of it I do not know what to do to access semantic level tags. I am curious how to modify just the style classes from C# (i.e. do not mess with the ASP.NET / id's). This is for design aspects as CSS does not have certain logic behind it and I cannot make another "html" selector in CSS or C#.

EDIT:

Class applied to a generic div element containing other elements. runat="server"

Upvotes: 0

Views: 737

Answers (2)

Dirty Developer
Dirty Developer

Reputation: 562

whatever controls you want to access in the code, should be runat="server" and with id.

< div id="dv" runat="server">...your design in between...< /div>

from the backend , you can access it like this:

dv.Attributes.Add("style", "color: green");

well, I suggest to have a css, and you can assign the class directly:

dv.Attributes.Add("class", "myClass");

or

dv.cssClass ="myClass";

Note: if you are looking for different themes can be applied on the user selection refer this link https://msdn.microsoft.com/en-us/library/ms366514.aspx http://www.c-sharpcorner.com/UploadFile/8dd3df/themes-in-Asp-Net/

Upvotes: 0

CodingYoshi
CodingYoshi

Reputation: 27009

Try this CSS parser. I think you will be able to accomplish your task. If not, it is open source, you can use it as a guide.

This code below will find "url('/images/logo.png')"

var parser = new Parser();
var stylesheet = parser.Parse(".someClass{color: red; background-image: url('/images/logo.png')");

var imageUrl = stylesheet.Rulesets
            .SelectMany(r => r.Declarations)
            .FirstOrDefault(d => d.Name.Equals("background-image", StringComparison.InvariantCultureIgnoreCase))
            .Term
            .ToString(); 

Upvotes: 2

Related Questions