Adding CSS to a Single Page

The project I’m working on has a page with an input form, and I  want to use CSS to format the form. Options for locating these styles include adding them in the main stylesheet used by the project, adding an embedded stylesheet to the page, creating a new CSS file and adding it to the master page, or creating a new CSS file and adding it to the page with the form.

I decided to create the CSS file and link it only page with the input form. In this project, linking to an additional CSS file is easier to implement than embedded styles, and should be easier to maintain in the long run. Adding styles to the main CSS file or linking from master file would mean that all the pages in the project would get the extra styles, not just the one that has the form.

This project is being developed in .NET, and is taking advantage of master files (a cool feature added in .NET 2.0) The <HEAD> section of the input form is coming from the master file, therefore I can’t simply add the link in .aspx file here. It has to be linked though the backend code. To do this, I added the following code to the Page_Load function:

// Add a CSS file to handle the formatting of the form
HtmlLink cssLink = new HtmlLink();

cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");

This code builds the link with the proper information, then adds it to the header of the page at runtime. Works like a charm when you have a stylesheet that only affects a few pages in your project.

%d bloggers like this: