Ryan Smith
Ryan Smith

Reputation: 8324

What's the best way to link to an external style sheet in SharePoint

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.

Upvotes: 1

Views: 2572

Answers (4)

tsilb
tsilb

Reputation: 8037

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

Upvotes: 1

Abs
Abs

Reputation: 1339

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();

Upvotes: 0

Ryan
Ryan

Reputation: 24452

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);
   }

Upvotes: 1

Ryan Smith
Ryan Smith

Reputation: 8324

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.

Upvotes: 0

Related Questions