Question

I have a simple website with a master-page. To set properties to elements on a content page (such as Textbox) I use CSS. In designer it works well but when I launch a site a style isn't apllied to controls. The reason is simple. To say, I have a TextBox with id="TextBox1" in content page, it is placed in ContentPlaceHolder1. In CSS file I set properties for object with id #TextBox1. When I launch a site due to master page name mangling it gets an id like ctl00_ContentPlaceHolder1_TextBox1 which is not defined in CSS file included in masterpage.

What is a correct solution of this problem? Hardcoding mangled name doesn't seem to be good.

Was it helpful?

Solution

Use CssClass on the controls, like this: CssClass="myClass", then in your stylesheet instead of this:

#TextBox1 { /* styles */ }

You'd have this:

.myClass { /* styles */ }

It's worth noting that .Net 4 fixes, or allows you to better manage the ID generated in the html, see here for details.

OTHER TIPS

As Nick and SLaks have both said classes are best. You can assign multiple classes in the class property and it will aggregate all the properties from all the classes specified overwrite any of the properties that it shares with earlier classes. The order of the classes definition in the css file sets the order that they get applied.

<style type="text/css">
.genericTextBox
{
background-color: #eee;
color: black;
}
.textbox1
{
background-color: #3ee;
font-size: larger;
}
</style>

<asp:TextBox id="textBox1" CssClass="textbox1 genericTextBox" runat="server"></asp:TextBox>

The order the styles get applied is first genericTextBox, because its the first defined in the style (essentially the order in class gets ignored). It sets the color and the background-color, then the style textbox1 gets applied and it overwrites the background-color and adds font-size to. So in the end you end with the color from generictextbox, the background-color and font-size from textbox1.

EDIT: on the TextBox changed class to CssClass

The simplest solution is to apply your CSS rules using classnames (Which don't get mangled) instead of IDs.

The correct solution is to use the ClientID property, which returns the mangled ID.

For example:

.Something #<%=TextBox1.ClientID %>` {
    color: red;
}

However, you can only do that for inline stylesheets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top