Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this navigation be done completely in CSS

I am a little stuck. I have created almost everything in the picture below. What I am stuck on is I am trying to figure out how I would set it up so that when a user clicks one of the links it makes the line below become red (after the next page loads). Obviously I would need to use Jquery to detect the page then add inline css, but what I am struggling with is I want this to be as easy as possible so that I can give this template to others and then they can add or remove items as necessary. I was trying to figure out if I could somehow use a li element to do this but I have not found a way yet. Does anyone have any ideas to help me?

enter image description here

like image 645
atrljoe Avatar asked Mar 23 '12 19:03

atrljoe


1 Answers

You could do it the way jackJoe suggests and set the active class server-side on the currently selected page, but you could also do this with pure CSS and a little advance planning.

This involves first setting the id attribute for the <body> tag of your page, which is a good practice to get into anyway. Then, your CSS file will take advantage of that body id to determine which <li> should appear as "active".

Sample page code:

<body id="main"> <!-- change this id for each page -->
    <ul>
        <li class="main-nav"><a href="#">Main</a></li>
        <li class="community-nav"><a href="/community">Community</a></li>
        <li class="search-nav"><a href="/search">Search</a></li>
    </ul>
</body>

Sample CSS:

li.main-nav,
li.community-nav,
li.search-nav
{
    background: #FFF;
    /* your other awesome styles */
}

#main li.main-nav,
#community li.community-nav,
#search li.search-nav
{
    /* style the active tab differently */
    background: #F00;
}

This way, the HTML code for the navigation section can stay completely static on every page. It doesn't have to be rendered server-side or modified dynamically on the client side.

There's a nice write-up about this technique available over on CSS Tricks: ID Your Body For Greater CSS Control and Specificity

like image 58
Cody Gray Avatar answered Oct 02 '22 07:10

Cody Gray