tags:

views:

716

answers:

4

I have some user controls that I'm loading in SharePoint and I would prefer to have all those styles contained in an external style sheet. What's the best way to link to an external stylesheet in CSS?

Thanks.

+1  A: 

Can you not add a <link rel...> to the head? If not, can you this.page.header.controls.add?

tsilb
A: 

Thanks,

I was looking at that way too complicated like. Your answer solved my problem and will actually work a lot better than the method that I was going to approach it from.

Ryan Smith
A: 

This code will ensure that you only add 1 stylesheet reference to a page regardless of how many web parts you have on it - same code snippet can be used for javascript.

protected override void OnPreRender(EventArgs e)
   {
      const string stylesheet = "YourStylesheet.css";
      if (!Page.IsClientScriptBlockRegistered(stylesheet))
         {
         Page.RegisterClientScriptBlock(stylesheet, 
            string.Format(@"<link href=""{0}/{1}"" rel=""stylesheet""/>",
                         this.ClassResourcePath, stylesheet));
         }
       base.OnPreRender(e);
   }
Ryan
isn't this for SPS 2003? How would this work with MOSS 2007?
Nathan DeWitt
Just checked - Page.IsClientScriptBlockRegistered is obsolete and will generate a compiler warning with anything above .NET 1.1
Nathan DeWitt
Yes you're right, replace Page.IsClientScriptBlockRegistered etc with the new ClientScriptManager http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.isclientscriptblockregistered.aspx
Ryan
A: 

If you're using MOSS, you can remove this configuration from your code entirely by using SharePoint's built in alternate style sheet property.

  1. Drop down the Site Actions menu, and select Site Settings->Modify All Site Settings.
  2. On the resulting page, click on the Master page link in the Look and Feel column.
  3. On the Site Master Page Settings page, scroll to the bottom to the Alternate CSS URL section. Select the Specify a CSS file... radio button and enter the URL of your style sheet. I put mine in the Home site's Style Library, but you can pretty much put it where you want.
  4. If you like, you can set it for all the subsites to by selecting the Reset all subsites to inherit this alternate CSS URL checkbox.
  5. Click the OK button.

Sadly,this configuration isn't available for WSS sites. But the object model does have it. So you can apply it with code in both WSS and MOSS, either in a web part or via something like PowerShell.

In code, once you have a reference to the the SPWeb object, say in a cleverly named variable called theWeb, you can just assign the URL of stylesheet with the following code:
theWeb.AlternateCssUrl = "http://server/site/library/stylesheet.css"; theWeb.Update();

Abs