How to add CSS Programmatically to an ASP.NET Page

I recently wrote an article on How to add a CSS Link programmatically using JavaScript. A user asked me how to do it in an ASP.NET page. It’s quite simple actually using the HtmlLink class which gives you programmatic access to the HTML <link> element.

Start by adding a reference to the System.Web.UI.HtmlControls namespace. Also make sure that your head tag has the runat=”server” attribute

<head runat="server">
title>Add CSS Dynamically</title>

Then add the following code in your code behind.


protected void Page_Init(object sender, EventArgs e)
HtmlLink link = new HtmlLink();
link.Href = "~CSS/FloatDes.css";
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");


Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim link As New HtmlLink()
link.Href = "~CSS/FloatDes.css"
link.Attributes.Add("rel", "stylesheet")
link.Attributes.Add("type", "text/css")
End Sub

Now run your page and check it’s source. You will see the link to the CSS file added in the head element as shown below:


Add CSS Dynamically

</title><link href="~CSS/FloatDes.css" rel="stylesheet" type="text/css" /></head>

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


urban said...

Perfect! Thanks for this nice tip!

Igor said...

I went a step over, I wanted a method that makes me impossible to include duplicates, something like ClientScriptManager.RegisterClientScriptInclude().
The solution is to give an ID to the control added in the Header section.

if (!String.IsNullOrEmpty(Key))
if (Page.Header.FindControl(Key) != null) return;

HtmlLink link = new HtmlLink();
if (!String.IsNullOrEmpty(Key)) link.ID = Key;
link.Href = StyleUrl;
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");

For the complete article I wrote:

Suprotim Agarwal said...

Nice! Thanks for sharing your solution here

J. Harlan Horn said...

Why not define a generic HTML <link> and set the HREF programmatically?

For example, in the source page <head>, add, "<link id="cssStyle" runat="server" rel="stylesheet" type="text/css" />". Then, in Page_Load set the Href property of cssStyle:
cssStyle.Href = "path/to/Styles.css";

Seems a bit cleaner and you have the control over placing the <link> in the desired order.