Monday, November 21, 2011

Styling ASP.Net with CSS

With ASP.Net you can set control properties to get colors and effects you want, but it is generally a better idea to use CSS to style your pages.

Setting the properties results in an inline style in the rendered HTML. This works and it is legal, but it it makes for a very hard to maintain web site. When you use in-line styles, it means if you want to change your sites look, you have to go to every single page and modify its controls separately. On the other hand, if you use CSS, you can change the whole look of a web site by editing just the one CSS file.

All web Controls render into xhtml before being displayed in the browser. So you can write CSS for the resulting xhtml objects rather than the ASP control itself. A GridView control, for instance, renders into a perfectly normal xhtml table. You can style it by styling the table elements. Below is an example of some CSS for styling a table that will apply to the DataGrid output. Note, it is not particularly sophisticated. It just shows the basics:

th
{
 font-weight:bold;
 color:White;
 background-color:Navy;
 border:solid,2px,White;
 padding-left:5px;
 padding-right:5px;
 
}

td
{
 border:solid,2px,Black;
 padding-left:5px;
 padding-right:5px;
}

Here is a picture of the styled table

You can also assign a CSS class to the cssStyle attribute of any ASP.Net control. Here is a simple Css class

.textback
{
 background-color:Teal;
}

Here is the ASP markup for applying the style

 <asp:TextBox ID="TextBox1" runat="server" CssClass="textback"></asp:TextBox>

Here is what it looks like when running

2 comments: