Web Part Styles

There are many examples of how to create a web part. However the best way to style web parts is not necessarily well documented, so I thought I'd offer up my approach and see what the community thinks.

Basically I create my web part as a feature in a solution. Then, if my web part generates any code that requires styling I add a .css file to my feature directory. Next I provision the stylesheet of my web part to a folder within my site's "Style Library". Finally I add the code into my web part to add the stylesheet ("<link>") link to the header of the page that my web part has been dropped on.

Most of the stuff is straightforward but here's how to provision a style sheet to the style library:

  1. Add a "provisioning.xml" file to your feature and reference it in the ElementManifest section of Feature.xml
  2. in "provisioning.xml" enter the following:

    <?xml version="1.0" encoding="utf-8" ?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Module Name="JumpToItemDropDownStyles" Url="Style Library/en-us/Core Styles/WebPartStyles" Path="Styles" RootWebOnly="TRUE">
    <File Url="JumpToItemDropDown.css" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" />
    </Module>
    </Elements>
And here's how to add your style sheet reference dynamically:

In your webpart code (I do it in CreateChildControls) add the following code:

try
{
ContentPlaceHolder header = (ContentPlaceHolder)this.Page.Master.FindControl("PlaceHolderAdditionalPageHead");
if (header != null)
{
CssRegistration cssControls = new CssRegistration();
cssControls.Name = "The Url To Your Provisioned CSS file";
header.Controls.Add(cssControls);
}
}
catch (Exception ex)
{
throw new Exception("CSS Registration Error.

details:
" + ex.Message);
}

Comments

Unknown said…
Hey,

Its true that it is hard to find documentation on styling webparts. But I still did not succeed with your explanation. I get the exception

Cannot make a cache safe URL for "styles/SisHvaEmployee.css", file not found. Please verify that the file exists under the layouts directory.

try
{
ContentPlaceHolder header = (ContentPlaceHolder)this.Page.Master.FindControl("PlaceHolderAdditionalPageHead");
if (header != null)
{
CssRegistration cssControls = new CssRegistration();
cssControls.Name = "SisHvaEmployee.css";
header.Controls.Add(cssControls);
}
}
catch (Exception ex)
{
throw new Exception("CSS Registration Error. details: " + ex.Message);
}

and I left the css file in path ..\12\TEMPLATE\LAYOUTS\STYLES


Hope you can explain me it a bit more?

Francois
Paul said…
Franske,

If you provisioned your file to the style library, as I did, then your url should be something like /Style Library/subfolder/myStyles.css

You can only use the /_layouts folder if the file is on the file system.

Popular posts from this blog

ERROR: Failed to create feature receiver...

Programmatically Update Page Layouts

Microsoft Virtualilzation Headaches