简体   繁体   中英

How to use custom CSS with my Sharepoint WebPart?

'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?

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM