Click here to Skip to main content
13,191,570 members (62,781 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


3 bookmarked
Posted 20 Jul 2010

Changing A Master Page Body Tag’s CSS Class for Different Content Pages

, 20 Jul 2010
Rate this:
Please Sign up or sign in to vote.
How to change a Master Page Body Tag’s CSS class for different Content Pages

It seems a bit of a failing of Master Pages that there’s no clear way to assign different CSS classes to the ‘body’ tag based on the Content Page. To get around this, I've taken to inheriting all of my content pages from a known base class (which in turn inherits from System.Web.Page) and then giving it a publicly accessible property of ‘BodyCssClass’!

namespace MartinOnDotNet.MasterPageBodyClass
    public class BasePage : System.Web.UI.Page
        public string BodyCssClass { get; set; }

This can then be picked up from the MasterPage and used to modify the body tag:

using System;

namespace MartinOnDotNet.MasterPageBodyClass
    public partial class Global : System.Web.UI.MasterPage
        protected override void OnPreRender(EventArgs e)
            BasePage current = Page as BasePage;
            if (current != null && !string.IsNullOrEmpty(current.BodyCssClass))
                Body.Attributes["class"] = current.BodyCssClass;
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Global.master.cs"
   Inherits="MartinOnDotNet.MasterPageBodyClass.Global" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" >
<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
<body runat="server" id="Body">
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">


The class itself can be assigned in the <%@ Page %> declaration of the Content Pages that implement the MasterPage:

<%@ Page Language="C#"
    Title="Content Page"
    BodyCssClass="content" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Martin Jarvis
Software Developer (Senior) Freestyle Interactive Ltd
United Kingdom United Kingdom
I'm a lead developer for Freestyle Interactive Ltd where we create many wonderful websites built on Microsofts ASP.Net and Ektron CMS.

I've been developing .Net applications (both Windows and Web) since 2002.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171017.1 | Last Updated 21 Jul 2010
Article Copyright 2010 by Martin Jarvis
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid