This project is read-only.

CSS per page or subsection of site?

Topics: Customizing Orchard, Writing themes
Mar 22, 2011 at 11:44 PM

We'd like to have some CSS elements that apply to only certain pages on the site, e.g. different background images.

Is this a reasonable way to do that? or is there a better way?

In Layout.cshtml for the theme we added:

        foreach (var fragment in WorkContext.HttpContext.Request.Path.Split('/')) {
            if (!string.IsNullOrWhiteSpace(fragment)) {

which adds a css class for each fragment of the page url.

That means we can do things like:

.products #content
  background: url(../Content/Images/productbanner.png) top right no-repeat;
which styles a page like /products/abcd 

Mar 23, 2011 at 12:04 AM

If that works it's actually pretty cool, I think.

Mar 23, 2011 at 12:06 AM

Works for me (without waiting for 1.1) ....

So, next question, any way to access the ContentType of the page that's being rendered?  I'd like to add that as a CSS class also.  Is it lurking somewhere in the dynamic WorkContent.Layout object somewhere?

Mar 23, 2011 at 12:27 AM

You should be able to inspect the shapes in Layout.Content and get ContentItem from there I suppose.

Mar 23, 2011 at 12:48 AM

Hi Hightechrider,

How does it work at different pages of different background images? Could you brief in details?




Mar 23, 2011 at 1:10 AM


The code fragment takes the URL path, splits it up at each / character and then adds each fragment to the css class list.  That gets added to the outermost div in Layout.cshtml where it does

var tag = Tag(Model, "div")

So a page with an url like /product/software-product/orchard-cms would become

<div class="product software-product orchard-cms">

Now you can use CSS classes to do anything you like that's specific to a page on specific elements on the page, e.g. put this in Site.css for your theme to style just the pages that are under the path .../software-product/...:

.software-product #content
  background: url(../Content/Images/productbanner.png) top right no-repeat;

You could modify the code to add more classes if you wanted, for example: one where you replace all the / characters in the path with - characters so you can have a class that's specific to one page, or perhaps add -last and -first to the first and last elements of the path too so you can be sure you aren't referring to some other part of the path in cases where it's ambiguous.


Mar 23, 2011 at 3:13 AM

Alright, thanks for your sharing.