Setting Menu Active State Using HTML and CSS

on June 11, 2012 in technology about

Setting menu active state should be simple in any programming languages or frameworks. Checking whether a page_id or an Object is the same as the current page in context is usually all that’s required.

When using a template engine, such as jinja in Django or python pelican, I sometime skip the extra logic in the templates and just bring it to the HTML/CSS layer especially if I have to insert the page_id at the <body> tag for one reason or another anyway.

Before:

HTML/Template:
<a href="/about/" {% if page_id == 'about-page' %}class="active"{% endif %}>About</a>

CSS:
.active { /** active state styles **/ }

After:

HTML/Template:
<body id="{{ page_id }}">...
...<a id="about-menu-item" href="/about/">About</a>...

CSS:
#about-page #about-menu-item, .active { /** active state styles **/ }

I like to have {% block body_tag %}<body>{% endblock %} in my base template file. That way, in other children templates like the archives.html of my pelican theme, I can have {% block body_tag %}<body id="archive-page">{% endblock %} without the need to set the page_id in the backend codes.

Like all things, when used in moderation and for the right situations, this technique can be a great addition to your bag of tricks as a front-end web developer.