Add class attribute to body element with ASP.NET web forms and Master Pages

Posted on August 27, 2009 by Frederik Vig in ASP.NET, Code Snippet

Often I have to add a class to the HTML body element. This is a little code snippet that allows you to easily do this.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %>
<!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="BodyTag">
    <form id="form1" runat="server">

Add the public property BodyClass.

public string BodyClass
        BodyTag.Attributes.Add("class", value);

Then in your .aspx, you need to make the Master Page strongly typed by adding MasterType (you can also manually cast it to the right type).

<%@ MasterType VirtualPath="~/Site1.Master" %>

You’ll now have access to the Master Pages BodyClass property.

Master.BodyClass = "home";
// Or by manually casting it
((Site1)Master).BodyClass = "home";
<body id="ctl00_BodyTag" class="home">

Related Posts: