ASP.NET & CSS: Using skins to “zero out” default style and set default CSS class names

I’ve moved this blog to https://damianedwards.wordpress.com. I won’t be updating this space any longer.
Please update your RSS subscriptions to https://damianedwards.wordpress.com/feed.

ASP.NET includes a feature called "Themes" that allows you to organise styling artifacts including CSS stylesheets and images into logical units that can be easily applied to a page or entire site through configuration. Part of this feature is the ability to create .skin files that set default values for certain properties of ASP.NET server controls as part of a theme.

Not all properties of ASP.NET controls are skinnable. Indeed the initial intention of .skin files was to enable the setting of default values for properties such as FontColor and BorderWidth, which when serving to CSS supporting browsers ASP.NET will render as inline style attributes on the emitted HTML controls. So what place do they have when we apply all of our style rules via way of attached CSS stylesheets and selectors (the way we should)?

Despite their evil initial purpose we can put .skin files to good use for two purposes:

  1. Assigning CSS classes to all instances of particular ASP.NET server controls; and
  2. Zeroing out the default inline style that ASP.NET sets on some controls.

So how does this work?

In your theme folder add a new .skin file called Controls.skin:

 Add a skin file to your theme folder

Now we want to add some declarations to the file to:

  1. Zero out the inline style of the ASP.NET validator controls; and
  2. Assign a default CSS class name to the Button, LinkButton, TextBox and validator controls.
<asp:RequiredFieldValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:RangeValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:CompareValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:RegularExpressionValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:CustomValidator runat="server" ForeColor="" CssClass="validation-error" />

<asp:LinkButton runat="server" CssClass="button" />
<asp:Button runat="server" CssClass="button" />
<asp:TextBox runat="server" CssClass="text-box" />

And that’s it! Now when ASP.NET renders these controls when they appear on a page (or in a site) with your theme configured, they’ll automatically pick up properties defined in this .skin file.



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