tags:

views:

3562

answers:

4

Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control. The style did not end up rendering to the output HTML. Even if it was possible, I'm sure it is bad practice to do this.

Is it possible to do this? I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply.

Update:

Per Jonathan's request, I was going to post the code. But, when I opened my project and loaded the page again (just for kicks) it ran correctly. My guess is that it had something to do with restarting the ASP.NET development server that Visual Studio launches when you run a page.

In any case, when I included identical multiple controls on the page, I got multiple identical styles as well. This would probably be the explanation why doing this is a bad thing. Regardless, it is always good to know best practices and alternative methods of accomplishing a task, so I do thank everyone for their answers.

+1  A: 

I think you will have to add it as an attribute to the server control... for it to render to HTML.

So basically (in C#),

ControlName.Attributes["style"] = "color:red";
Vaibhav
+1  A: 

but inline styles are bad bad.......much easier to use a css class, even in prototypes

redsquare
Yeah, I know it's bad, hence the dislaimer in the question. This question is just out of sheer curiosity.
Jason Z
+1  A: 

Intellisense won't give you hints but you can do this:

<asp:Label ID="Label1" runat="server" Text="Label" style="color:Red;"></asp:Label>
Alison
+5  A: 

According to the W3CSchools site:

The style element goes in the head section. If you want to include a style sheet in your page, you should define the style sheet externally, and link to it using .

So it's not a good idea to include style elements (e.g. a <style type="text\css"></style> block) in a control. If you could, it'd probably have an effect in some browsers but it wouldn't validate and is bad practice.

If you want to apply styles inline to an element then either of these would work:

C#

myControl.Attributes["style"] = "color:red";

myControl.Attributes.Add("style", "color:red");

VB.NET

myControl.Attributes("style") = "color:red";

myControl.Attributes.Add("style", "color:red");

But bear in mind that this will replace any existing styles that are set on the style attribute. This may be a problem if you try setting styles in more than one place in the code so is something to watch out for.

Using CSS classes would be preferable as you can group multiple style declarations and avoid redundancy and page bloat. All controls derived from WebControl have a CssClass property which you can use, but again be careful not to overwrite existing classes that have been applied elsewhere.

tjrobinson