Adding CSS links to your SharePoint pages or code…

I love Twitter – you get some though provoking questions on it. Thomas Resing asked the other day:

How are you applying styles to your custom web parts in #SharePoint? using CSSClass property, stuck on deploying css <Link> tag in the head

Well, for pages themselves you have the CSSRegistration control. It’s an ASP.NET control, and looks something like:

<SharePoint:CssRegistration name="/_layouts/myBrand/SomeStyle.css" runat="server"/>

This control registers the URL with the page, but doesn’t emit anything. That’s controlled by the CssLink control:

<Sharepoint:CssLink runat="server" />

It actually outputs the <link> elements, and this means that you can have a CSSRegistration control low down in the page (in a Content control, for example) and you can still output it in the <head> of your page. There’s a good post about this on CleverWorkarounds.

So, could we use that control? Well, we should be able to instantiate one – except it turns out that we don’t have to. We can just use the CSSRegistration.Register() static method – something like:

protected override void CreateChildControls(){

Job done…

Adding CSS links to your SharePoint pages or code…

2 thoughts on “Adding CSS links to your SharePoint pages or code…

  1. Nice tip. A couple of things to remember when using this. If you just use CssRegistration.Register(“SomeStyle.css”) it expects the file to be in http://website/styles/SomeStyle.css so adjust accordingly (it’s a good practice to put it in a subfolder of your own name). Also, you can’t use this trick to read files from the wpresources directory of the website directory as it tries to make a cache safe URL and can’t resolve “~/wpresources” in code.

  2. Good points.

    I’m pretty sure I’ve use /_layouts before (ages ago) but I’d have to check that really does work. The short of it – check your URLs

    And I’ve gotta admit, I didn’t know that about the wpresources – I think when I did this is was a user control. I’m actually not sure I’ve ever really used wpresources…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.