Anyname Donotcare Anyname Donotcare - 1 year ago 52
ASP.NET (C#) Question

How to use CSS in ASP.NET application

I want to know to use CSS in ASP.NET.

If I have set of CSS files and I link my master page to them, how to utilize them to make my application look good. I'm not talking about CSS itself but about how to use its elements in the source of any ASP.NET page.

I'm looking for suggestions, resources, sites, or opinions.

Answer Source

Well, assuming you want quick yet efficient answer, I'll share my view of how to use CSS files and CSS in general, it's not really related to controls or ASP.NET language.

First of all, ask the graphic designer to give you sketch of how the website should look: position of each element (menu, logo, content), look and feel of each element (color? picture if needed?) and maybe most important, uniform font family and colors all over the site: there might be several colors, but more than three or four becomes too messy and noisy.

Having the sketch, start by placing empty placeholders (or with dummy text) in the page, and give each its own class where you'll later define how the content in the placeholder is going to look like. You can also use the ID of the placeholder element later if you are sure its design is unique and won't be "shared" by other elements.

The "heart" of all this is making everything appear as it is in the sketch by defining the proper style. For example if you need menu on the right with links in specific color and contents on the left, all you need in the HTML part (.aspx or .ascx in your case) is this:

<div id="MainContents">contents here</div>
<div id="MainMenu">menu links come here</div>
<div class="clear"></div>

Then in the CSS file:

#MainContents { float: left; width: 700px; padding: 10px; }
#MainMenu { float: right; width: 300px; padding: 5px; }
#MainMenu a { color: #e01010; }
.clear { clear: both; }

The "clear" part is required when using float, just an empty div with the clear: both style.

That's about it, in a very shallow nutshell... I'll elaborate on specific part if you want.

Regarding ASP.NET controls, if more than one control is using the same CSS file and that CSS file is not "global" to all pages, you can use such code to include the CSS file only once:

if (!Page.ClientScript.IsClientScriptBlockRegistered(this.Page.GetType(), "MyCssFile"))
    Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "MyCssFile", "<link href=\"MyCssFile.css\" rel=\"stylesheet\" type=\"text/css\" />", false);

This code, placed in the Page_Load of the control, will include the CSS file only once even if there are 20 instances of the control in the page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download