Post Pic

Using Umbraco and Razor Syntax to add attributes to body tag for CSS targetting

I never found a solution that I was happy with for adding unique id’s to a page body tag that didn’t feel like a hack. I often need to do it for very specific CSS targeting so I introduce to you my current solution using the new Razor syntax inside of a master template in Umbraco.

<umbraco:macro runat="server" language="razor">

<body id="@Model.Id">


UPDATED: The example above has now been updated to simplify it and require just a single piece of code inside of the inline-macro “@Model.Id” to output the current page id.

Essentially all this is doing is appending the current node id to a string (in my case just the letter ‘p’) and adding it to the id attribute of the html body tag.

I tend to also need to take this one step further and include the id of a parent page in case styling is applied to a section of the content tree, I do this by adding a class to the body tag which contains the section id. The solution for this that I have used successfully on a current project is as follows:

<umbraco:macro runat="server" language="razor">

	var node = Model;
	var sid = "s" + Model.Id;
	var level = 2;

	while(node.Level > 1)
		if (node.Level == level)
		  // Add any logic in here then create your class
		  sid = "s" + node.Id;
		node = node.Parent;

<body id="@Model.Id" class="@sid">


As in the previous example I am appending the current page id to a string and adding it to the id attribute of the body tag. I am also using a while loop to walk up the content tree to a specific level in the content tree, which in this case is level 2 and I am getting the id of the page at the specified level and appending it to a string(which in this case is ‘s’) and adding it to the class attribute of the body tag.

So what have I gained by doing this? I can now apply specifically targeted CSS styling to individual pages or to an entire section of the content tree.

I would welcome any comments from those more familiar with Razor in Umbraco on the performance overhead of doing this on each page load since I am including this in my master page.

* Credit goes to Jonas Eriksson for his tip on the Razor syntax for accessing parent nodes and to Aaron Powell for his introduction to “Using Razor in Umbraco 4” blog post.

Umbraco Certified Developer
SagePay Approved Partner
Creative Market