tags:

views:

51

answers:

2

How can I register a css code block inside an ascx control?

Can I just have

<head id="head" runat="server">
    <style type="text/css">
        .customClass
        {
        background-color: Lime;
        }

        </style>
</head>

Anywhere in ascx page? I doesn't seem to work?

+3  A: 

You have three options to insert CSS into a page:

  • External style sheet
  • Internal style sheet
  • Inline style

The style element must be enclosed within the head element. If you are attempting to style elements contained within a user control you can use any of these three options. As a note (mostly my opinion) inline styling is 99.9% of the time the wrong decision.

One option is to expose a ContentPlaceHolder in your Site.Master inside the head section. Then using this ContentPlaceHolder on pages where you use your user control you'll be able to place a link element specifying a style sheet for your user control.

Another option is to simply put the styling rules for your user control in the style sheet used for your entire site.

ahsteele
+2  A: 

Styles must be defined in the head section of your HTML. That goes for both style tags and link tags that register external CSS files.

If your page has a head tag with the runat="server" attribute, you can programmatically access it via the property this.Page.Header.

The method I usually use when I need to add something between the opening <head> and closing </head> tag is a method such as this one. Simply pass in the url to your stylesheet.

public void AddStylesheet(string url)
{
    string link = String.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" />", url);
    this.Page.Header.Controls.Add(new LiteralControl { Text = link });
}
wsanville