Nima Dilmaghani’s Technology Blog

10 Rules for effective use of CSS in ASP.NET

Posted in .NET, ASP.NET, Cascading Style Sheets, CSS, engineering, expression', html, web design by nimad on October 2, 2007

Becoming standards compliant, effective, and successful when using Cascading Style Sheets (CSS) with ASP.NET is not always obvious, straightforward or easy. Here I am putting together a series of tips and best practices that can help you on the way.

  1. Always prefer CSS over ASP.NET’s Skins for the following reasons:
    • CSS is a well accepted standard.
    • Designers understand CSS but may not understand ASP.NET’s proprietary mechanisms.
    • Skins lead to Classitis. Each skin creates an html class attribute that has its associated styles. This does not follow the principle of reuse.
    • A well designed external CSS implementation will have a smaller payload and faster download times than its equivalent Skin implementation.
    • Microsoft is heavily investing in tooling for CSS design (Expression Web and inclusion of the Expression Web engine in VS2008), and is really not doing anything more with Skins. So follow their lead. Going forward CSS will have the best tooling support from Microsoft.
  2. Use CSS within the Themes construct in ASP.NET in order to get all the good CSS support in VS2008. In particular, instead of linking to CSS files in the <head> section of your HTML document,
    • Create one or more theme folders under the App_Themes folder.
    • Put your CSS files inside these themes folders.
    • Link to these themes by setting the Themes attribute in the page directive.
  3. When you drag a control from the toolbox onto your form, ASP.NET, depending on the control, may add inline styling to your control. Delete these inline styles in Code View, otherwise due to the specificity rules, they will override anything you set in the CSS files and you will be scratching your head trying to figure out what happened while trying to find out why the styles you specified are not applied.
  4. Furthermore, note that most ASP.NET controls have several formatting properties that can be set via the properties window or directly in the markup. All of these will end up becoming inline styles and should totally be avoided. The only formatting property that I recommend using (in moderation to avoid Classitis) is CssClass.
  5. CSS files are written against pure HTML elements not ASP.NET Server Controls. Therefore, understanding the mappings between the two is vital to writing quality CSS files and separating the structure (HTML) from the presentation (CSS). See the bottom of this post for the mappings.
  6. Understanding the mappings between ASP.NET web control and HTML types is is also vital for making sure that your site is following well established web design standards and guidelines. If you consider using an ASP.NET web control, you need to make sure that the corresponding HTML type was intended for that usage. For example, you can use a LinkButton to submit values to the server. However, the LinkButton converts to an <a href> element (along with some JavaScript that does the postback). The <a href> element is intended for hyperlink. The HTML 4.01 specification clearly states: “A link is a connection from one web resource to another.” To submit data to a server, it is better to use the Button control which converts to input type=”submit”. Why is following these standards important? For example, if we choose the LinkButton over the Button control, if the user has JavaScript turned off, the site will no longer function properly. Also following standards is probably the most important step to making your site accessible.
  7. Often times one has to choose between an ASP.NET Server Control and the corresponding HTML element. Here are some rules of thumb. For simple controls like a TextBox or a Label, if you need to map the control to ASP.NET server side functionality, or if you would like to take advantage of the ASP.NET validation controls, use ASP.NET controls. If you don’t, use the lighter html controls. Obviously sophisticated controls such as the Calendar Control can save you hours of development time since they have no equivalents in HTML. On the other end of the spectrum, do not forget that there are a good number of HTML elements that do not have (and should not have) ASP.NET counterparts. An example is <input type=”reset”>. Use these as necessary to do your work.
  8. Use the YUI Library CSS Tools. They will save you many hours of work. These tools consist of four style sheets that Yahoo uses for their own production websites. They include a reset style sheet that neutralizes browser specific styles, a base style sheet which creates a consistent style foundation for common HTML elements, a style sheet for setting and managing fonts, and a grid style sheet for managing grids. If you like, Yahoo will even host these sheets for you.
  9. Note that you can use ID selectors only with HTML elements. The ID you assign to an ASP.NET Control will most probably change as the HTML is rendered for the control. So for ASP.NET Controls, use the CssClass attribute to define the style. If the control does not have this attribute, wrap it in a <Div> tag. Wrapping in Div tags should be the last resort. Usually you can refactor your CSS by using contextual selectors on Div tags that wrap a group of elements.
  10. The designer behaviors in both VS2008 and Expression Web (note that they have the same engine so they work pretty much the same way) focus on styling ASP.NET controls using ID Selectors. This can easily be changed to class selectors. So for a complex ASP.NET web control you add the CssClass attribute with a value. Then, in the CSS file, you add details to it. The CSS designers help you set the CSS properties of the control itself, but to set the properties of individual elements in the control, you need to go in the CSS file and hand code. Remember two powerful CSS selectors, contextual selectors and attribute selectors. (Note that attribute selectors are not supported in IE6 or older browsers). Here is a simplified example:

 

<asp:RadioButtonList runat=”server” CssClass=”FunkyRadioButtonList”>

<asp:ListItem>first</asp:ListItem>

<asp:ListItem>second</asp:ListItem>

<asp:ListItem>third</asp:ListItem>

</asp:RadioButtonList>

 

.FunkyRadioButtonList

{

/* general styling for the container control goes here*/

}

 

.FunkyRadioButtonList input[type=”radio”]

{

/*styling specific radio buttons in the FunkyRadioButtonList goes here*/

}

 

 

 

 

The list below shows the ASP.NET Server control and the HTML element that is generated from it by the ASP.NET runtime.

 

ASP.NET Control HTML Element
Label span
TextBox input type=”text”
TextBox TextMode=”MultiLine” textarea
TextBox TextMode=”Password” input type=”password”
Button input type=”submit”
LinkButton a href=”javascript:__doPostBack(‘LinkButton1’,”)”
ImageButton input type=”image”
HyperLink a
DropDownList select
ListBox select size=”4″ gives you 4 rows
ListItem option
CheckBox input type=”checkbox”
RadioButton input type=”radio” followed by a label for the text
RadioButtonList table with a tr with one td for each radio button. Inside each td there
is a input type=”radio” and a label
Image img
ImageMap img and a map tag holding one or more of the following 3:
CircleHotSpot area shape=”circle”
PolygonHotSpot area shape=”poly”
RectangleHotSpot area shape=”rect”
Table table
TableHeaderRow tr
TableRow tr
TableFooterRow tr
TableHeaderCell th
TableCell td
BulletedList ul with each list item:
ListItem li
HiddenField input type=”hidden”
Literal Literal is not translated to any html element. The dynamic content
returned by the methodname method is directly displayed.
Calendar a rather sophisticated table
AdRotator a
FileUpload input type=”file”
Wizard a rather sophisticated table. You can Convert the Wizard Control and
related controls such as the CreatUserWizard control into templates, and
then modify the html, remove the tables, and replace them with divs to make
them CSS friendly. Even after all this, the wizard navigation buttons
will still be unreachable via CSS. Therefore, I hand code these
functionalities instead of relying on the Wizard for full control.
Xml <?xml version=”1.0″ encoding=”utf-8″?>
MultiView MultiView and all the Views inside of it are not translated to any html
element. Thier content is directly displayed.
Panel div
PlaceHolder Placeholder is not translated to any html element. The controls added to
it by the PlaceHolder1.Controls.Add() methodare directly displayed.
Substitution Substitution is not translated to any html element. The dynamic content
returned by the methodname method is directly displayed.
Localize Localize is not translated to any html element. It’s content is directly
displayed.
Validation controls span
Advertisements

35 Responses

Subscribe to comments with RSS.

  1. […] 10 Rules for effective use of CSS in ASP.NET […]

  2. Matt said, on October 9, 2007 at 3:36 pm

    This is a great, great post. I hope more people start to code this way. Just a few additions:

    The asp:Label control isn’t always rendered as a <span>. If the AssociatedControlID property is set, it’s rendered as a <label>, with the for attribute set.

    The asp:RadioButtonList control isn’t always rendered as a <table>. It comes out as a <span> if RepeatLayout is set to Flow.

    Also, a sidenote: I usually create a (very small) default skin for every project, and import it using the StyleSheetTheme property in web.config. I use it to add a default CssClass to commonly-used controls like asp:TextBox, asp:FileUpload, and asp:Button. This saves me the trouble of adding the same CssClass to the same controls over and over, but because I import with StyleSheetTheme instead of Theme, I can still override that default whenever it’s appropriate.

  3. Fardoche said, on October 12, 2007 at 4:01 pm

    any info on how to use YUI theme inside an ASP.NET project? how to apply and get the power of javascript?

  4. adolfojp said, on November 22, 2007 at 9:16 am

    Labels don’t always render as spans. If you assign a value to their AssociatedControlID property they get rendered into html labels.

    I prepend ASP.NET Labels with “lbl” or “for” depending on their purpose and generated counterpart to avoid confusion.

    Just my 2 cents.

  5. Wanderson Santos said, on April 29, 2008 at 10:19 pm

    Excellent! Thanks for this contribution!

    @Matt
    Thank you too. Your solution appears to be the best of both worlds.

  6. Jitendra Vyas said, on July 19, 2008 at 11:07 am

    this is a awesome post. very good information for a css developer

  7. Atom said, on September 29, 2008 at 5:52 pm

    One more important addition:

    When you use a Panel, if you set the GroupingText, it adds a “fieldset” and a “legend” tag (As it assumes you want the panel to be a form.

    Unfortunately, ASP.Net still renders the div (instead of only the fieldset), but it’s not the end of the world that we get an extra div.

  8. kiran said, on February 20, 2009 at 6:48 pm

    its awasome for developers

  9. alabdia said, on November 10, 2009 at 2:28 am

    Good evening! buy nolvadex in the usa http://www.stumbleupon.com/stumbler/med-brother/ buy nolvadex drug Please, thank your sister for me.

    I’ll just like to tell you that… buy cheap nolvadex buy nolvadex in the usa
    buy nolvadex drug See you tomorrow!

  10. bradwellau said, on March 18, 2010 at 11:38 am

    area unfccc results led google web cupcake functionality

  11. shweta@bestmanagmentservices said, on January 6, 2011 at 9:26 am

    really this post is very helpful for css beginner.thanks

  12. jones said, on March 29, 2011 at 1:10 am

    wUieeK http://djIjw3MnccVop6a5hFgql.com

  13. Ewrlsjcp said, on August 1, 2011 at 3:58 am

    I love this site free lolitas real hardcore >:-]]]

  14. Grtxqgkb said, on September 2, 2011 at 8:15 pm

    My battery’s about to run out busty swimsuit models 800

  15. Ecppfwip said, on September 5, 2011 at 5:32 pm

    What qualifications have you got? preteen wet bikini
    %-DDD

  16. Ypyrzoqp said, on September 7, 2011 at 2:10 am

    I’d like to withdraw $100, please free preteen models
    >:-(((

  17. Vvxvduwl said, on September 7, 2011 at 6:18 pm

    Not in at the moment livedoor bbs
    btrbh

  18. Qcirnlgn said, on September 8, 2011 at 1:57 am

    Could I have an application form? pedo nude
    ybuahv

  19. Xhtcrefc said, on September 22, 2011 at 9:07 am

    Best Site Good Work Underage Animal Sex Stories 8OOO

  20. celsa said, on March 26, 2013 at 6:59 pm

    This is certainly the fourth blog, of your blog I really
    went through. Yet I personally love this particular 1, Modern Window Treatments “10 Rules for
    effective use of CSS in ASP.NET | Nima Dilmaghani’s Technology Blog” the very best. Thank you -Lilly

  21. Sheena said, on May 2, 2013 at 1:34 am

    Anti Aging formulas which are claimed to be 100 % natural contain just some natural compounds to
    make consumers to believe that they are getting natural products.
    This means that, you can use almond oil to massage your body whether you have normal, dry or oily skin.
    We don’t typically take natural ingredients into consideration when we plan our daily and weekly beauty routines.

  22. reputation management said, on May 2, 2013 at 4:32 pm

    It’s actually a cool and useful piece of info. I’m happy that
    you shared this helpful information with us. Please keep us up to date like this.
    Thank you for sharing.

  23. Rajendra said, on July 16, 2013 at 1:41 am

    thanks, very excellent…

  24. Sondra said, on June 15, 2016 at 8:17 am

    fantastic put up, very informative. I’m wondering why the
    other specialists of this sector do not realize this.
    You must continue your writing. I am sure, you have a
    huge readers’ base already!

  25. Deneen said, on August 13, 2016 at 1:35 am

    New building condos have a specific collection of guidelines while existing condos
    have a slightly different set of rules.

  26. codecademy.com said, on August 13, 2016 at 8:59 am

    The FHA minimised the waiting period to one year if you could show you looked at a foreclosure, brief sale, insolvency,
    or act in lieu of repossession due to an exterior economic occasion, like a loss of revenue or work (or a combination of both) with no fault of your personal.

  27. fha streamline refinance rules said, on August 14, 2016 at 8:08 pm

    After the subprime crisis, it has actually been harder
    for newbie residence customers to qualify for a home mortgage
    FHA loans are still less complicated to get as well as have some benefits over traditional home mortgages.

  28. cama elastica said, on September 17, 2016 at 8:48 pm

    It’s in reality a nice and useful piece of information. I’m glad that you simply
    shared this useful information with us. Please keep us up to date like
    this. Thanks for sharing.

  29. centrifuga said, on September 27, 2016 at 1:28 am

    If you are going for finest contents like myself, just pay a quick
    visit this web page daily as it offers feature contents,
    thanks

  30. asse da stiro said, on October 5, 2016 at 7:30 am

    I drop a leave a response when I especially enjoy a article on a site or if I have
    something to add to the conversation. It is a result of the fire communicated in the post I browsed.
    And on this post 10 Rules for effective use of CSS in ASP.NET | Nima Dilmaghani’s Technology Blog.
    I was excited enough to post a thought 🙂 I do have a couple of questions for you if you do not mind.
    Could it be just me or do a few of the remarks come
    across like they are coming from brain dead folks?
    😛 And, if you are writing at additional online social sites,
    I would like to keep up with anything fresh you have to post.
    Would you make a list every one of all your social pages like your linkedin profile, Facebook page
    or twitter feed?

  31. Skin Royale And Eye Royale said, on October 20, 2016 at 7:57 pm

    I got what you mean,saved to fav, very nice website.

  32. AdultWork-VIP.com said, on December 28, 2016 at 8:51 pm

    They care cool because they may be seen in kitchen while cooking for their families.
    But now that technolgy has allowed communication to happen, istance has become eliminated high
    are lots of people who meet even iif they cannot interact physically.
    The Reason Why Shhe Joined A Seoul Personals Dating Site – This might be an extremely obvious one andd need to be answer.

  33. σχεσεις ζωδιων said, on March 8, 2017 at 4:25 pm

    Appreciation to my father whoo shared with me regarding this weblog, this weblog is
    genuinely awesome.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: