Thursday, August 30, 2007

CSS Friendly menus with no 3rd party controls.

Drop the following into your page class:

void BuildMenus(SiteMapNode node)

{

if (node.ChildNodes.Count == 0) return;
Response.Write("<ul>");
foreach (SiteMapNode child in node.ChildNodes)
{

Response.Write("<li>");
if (child.Url.Length > 0) Response.Write(string.Format("<a href=\"{0}\">", child.Url));
Response.Write(" ");
Response.Write(child.Title);
if (child.Url.Length > 0) Response.Write("</a>");
BuildMenus(child);
Response.Write("</li>");

}
Response.Write("</ul>");

}


Then call this from your page with the following:

<div id="masterMenu">
<%BuildMenus(SiteMap.RootNode); %>
</div>


Note the outside div.

Now comes the fun. Add the following to your CSS.

#masterMenu ul, #masterMenu ul ul
{
border: none;
background-color:#225faa; /*#004E99;*/
padding-left: 0px;
cursor: default;
display:inline-block;
}
#masterMenu ul li
{
width: auto;
list-style-type: none;
position: relative;
color: #fff;
float: left;
display: inline-block;
padding:0 4px 0 4px;
}
#masterMenu ul li > ul
{
display: none;
position: absolute;
top: 16px;
left: -40px;
width:150px;
}

#masterMenu ul li > ul li
{
width:142px;
}

#masterMenu ul li:hover
{
background-color: #FFFF99;
color: #000;
}
#masterMenu ul li:hover > ul
{
display: block;
}
#masterMenu ul li a
{
color: #fff;
display: block;
width: 100%;
text-decoration: none;
}
#masterMenu ul li a:hover
{
color: #000;
width:auto;
}

#masterMenu ul li:hover > a
{
color: #000;
}

Now, aren't you glad you can just cut and paste from me? Sure you are.

Good luck