Reputation: 2427
Can you put CSS style block (ie <style type="text/css">...</style>
) on an ascx page, in order to style the user control? I tried it and it works. However I wonder if this is a common practice and the problem is the style block is inserted into the final HTML right where the user control is supposed to be. My understanding is style blocks should be between the <head></head>
tags at the front. So it does seem to be out of place. BTW can javascripts be put any where on the HTML?
Upvotes: 0
Views: 2017
Reputation: 9802
Use these helper methods which I store in a globally accessible HTMLHelper class as a static method:
/// <summary>Register a CSS block in HEAD</summary>
/// <param name="page">A reference to the current Page instance (usually this.Page from a page or control)</param>
/// <param name="id">An ID used to track if this style block has been added before or not. Must be a unique ID in the HTML</param>
/// <param name="cssText">The CSS text</param>
public static void RegisterCSSBlock(System.Web.UI.Page page, string id, string cssText)
{
if (page != null && page.FindControl(id) == null)
{
HtmlGenericControl css = new HtmlGenericControl();
css.ID = id;
css.TagName = "style";
css.Attributes.Add("type", "text/css");
css.Controls.Add(new LiteralControl(cssText));
page.Header.Controls.Add(css);
}
}
This is easily adapted for CSS files (rather than code). You don't need to adapt it for JavaScript as the built in ClientScriptManager methods already handles this well.
Upvotes: 0
Reputation: 7545
Javascript tags can be placed just about anywhere. The head seams like the logical place to put it but some people recommend placing it at the very bottom just before </body>
. This way the content of your page should load faster and might improve SEO.
Stylesheets should definitely be placed in the <head>
as it is a W3C recommendation.
When using stylesheets take Tim's advice to sneak them into the head, or better yet just use an external .css file.
Upvotes: 1
Reputation: 5480
Yes, <style>
tag and <script>
tag can be insert anywhere in html. It must not have to be in <head></head>
. Do take note that browser loads html from top to bottom. If you specify css class for a particular control in your html before declaring <style>
reference, you may not get the desired styling effect. Same thing for <script>
.
Upvotes: 0
Reputation: 20364
I you have runat="server" in your head tag, then you can dynamically add the CSS or Script tages to that.
Dim lt as New Literal()
lt.Text = "<style type='text/css'>styles......</style>"
Page.Header.Controls.Add(lt)
lt = New Literal()
lt.Text = "<script type='text/javascript'>scripts.....</script>"
Page.Header.Controls.Add(lt)
Upvotes: 2