13

'ello!

I'm developing my first WebPart for Sharepoint, and now I'm wondering where/how to include/store my CSS. Where should I put my .css files? How should I include them in my webpart?

4 Answers 4

18

This is my Approach

protected override void CreateChildControls()
{
    CssRegistration.Register("/_layouts/STYLES/WebPartName/styles.css");
}

This ensures the CSS is registered and included only once and gives the opportunity to modify the CSS without redepolying the whole dll.

Sign up to request clarification or add additional context in comments.

Comments

8

You should use Web Part Resources which can be linked or embedded. This article does a good job of explaining how to use them:

Best Practices for Managing Web Part Resources

2 Comments

That article is good except the part where he's hardcoding the path ("~/wpresources/namespace" etc) depending GAC/Bin install. Thats what WebPart.ClassResourcePath is for - msdn.microsoft.com/en-us/library/…
Link is dead. Here's a internet archive snapshot : web.archive.org/web/20110429103446/http://…
1

U can also use:

HtmlLink linkCss = new HtmlLink();

//Defining attributes and values of the link tag
linkCss.Attributes.Add("href", "StyleSheet1.css");
linkCss.Attributes.Add("type", "text/css");
linkCss.Attributes.Add("rel", "Stylesheet");

//Add HtmlLink instance to the header of the current page
Page.Header.Controls.Add(linkCss);

Comments

0

Embedding the css into the webpart is fine if you never ever plan to change the CSS for the webpart.

I would recommend you include the css in either a separate file stored in the style library or change a css file linked in the page layout or master page (such as core.css).

Just define unique classes for your webpart if required and leave the definition of how that renders to each website. This allows different areas of your SharePoint implemenation to show the same webpart in different ways.

The means you will never have to release a dll in order to change a minor look and feel issue.

1 Comment

I agreee that linked rather than embedded is the way to go for updates - but I think its a bad idea for the css to be associated with the page, in that case how can you be sure when a web part is added to a page that the css is there too? You are also adding it to every page regardless of need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.