I'm developing a web part which needs some custom CSS files. So I'm using the CssRegistration class to add them to the page header.
The code registers 4 CSS files which got deployed to the layouts folder by the web part feature. A fifth CSS files is optionally registered when there's a path to it set in the web part's property AdditionalCss
. The CSS files should be inserted in the header after all SharePoint CSS files and should be sorted in the order they were added by code.
The code I used is the following:
var contentCss = new CssRegistration
{ Name = "/_layouts/MyWebPart/css/content.css",
RevealToNonIE = true };
if (SPContext.Current.Web.UIVersion == 4)
contentCss.After = "corev4.css";
else
contentCss.After = "core.css";
Controls.Add(contentCss);
var customCss = new CssRegistration
{ Name = "/_layouts/MyWebPart/css/cn_custom.css",
After = contentCss.Name, RevealToNonIE = true };
Controls.Add(customCss);
var styleCss = new CssRegistration
{ Name = "/_layouts/MyWebPart/css/styles.css",
After = customCss.Name, RevealToNonIE = true };
Controls.Add(styleCss);
var colorsCss = new CssRegistration
{ Name = "/_layouts/MyWebPart/css/colors.css",
After = styleCss.Name, RevealToNonIE = true};
Controls.Add(colorsCss);
if (!string.IsNullOrEmpty(AdditionalCss))
{
var webPartCustomCss = new CssRegistration
{ Name = AdditionalCss,
After = colorsCss.Name,
RevealToNonIE = true };
Controls.Add(webPartCustomCss);
}
When I add the web part to a page all CSS files are added to the page as expected. Except the files are sorted in the wrong order.
Without the custom CSS file the order is: (link's rel- and type-attribute were removed for a better overview)
...
<link href="/_layouts/1033/styles/Themable/corev4.css"/>
<link href="/_layouts/MyWebPart/css/colors.css"/>
<link href="/_layouts/MyWebPart/css/content.css"/>
<link href="/_layouts/MyWebPart/css/cn_custom.css"/>
<link href="/_layouts/MyWebPart/css/styles.css"/>
With the custom CSS file the order is:
...
<link href="/_layouts/1033/styles/Themable/corev4.css"/>
<link href="/_layouts/MyWebPart/css/cn_custom.css"/>
<link href="/sites/mysite/Style%2520Library/de-de/test.css"/>
<link href="/_layouts/MyWebPart/css/styles.css"/>
<link href="/_layouts/MyWebPart/css/content.css"/>
<link href="/_layouts/MyWebPart/css/colors.css"/>
As you can see both cases provide a totally different order and the CSS files were never sorted in the order they were added by code.
With this strange behavior the whole CssRegistration class is not very useful as you cannot relay that the CSS files are always in the same order. This makes designing with CSS nearly impossible.