Monday, October 26, 2009

ASP.NET - CSS ID selector vs. CSS class for custom server controls

To have a common use control, we do create custom ASP.NET server controls.
As a simple example let's have a side bar control. To do that, Add a Web User Control, it has .ascx extention and call it sideBarList.

<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="sideBarList.ascx.cs"
Inherits="AspAdvWrk01.sideBarList" %>

<asp:Panel ID="srchEnginePnl" runat="server">
<h4>Search Engines:</h4>
<a href="http://www.bing.com/">bing</a><br />
<a href="http://www.google.ca/">Google</a><br />
<a href="http://m.www.yahoo.com/">Yahoo</a><br />
<a href="http://www.msn.com/">MSN</a><br />
<a href="http://www.altavista.com/">Altavista</a>
</asp:Panel>

Then let's add the following CSS codes in a style sheet:

#srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}

I tried the same ID name of asp Panel control in this style sheet as a CSS ID selector, To apply style to the asp Panel control with ID name of srchEnginePnl. Even though that we have CSS ID selector but it doesn't apply any style because the real ID name in HTML page is something else which you can find it by checking the html source of the page in your browser (in the test page it was #ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl).

The solution, a CSS class selector and utilizing CssClass attribute as following:

.srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}

a.srchEnginePnl
{
padding: 10px;
}

...
<asp:Panel ID="srchEnginePnl" CssClass="srchEnginePnl" runat="server">
...

otherwise you have to use the real ID of your panel control in html source and use that ID name to define the ID CSS selector in your style sheet:

#ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}

...
<asp:Panel ID="srchEnginePnl" runat="server">
...

Share/Bookmark

No comments: