Search code examples
ruby-on-railsmenuhighlight

Ruby on Rails highlight current link on navigation bar?


Can anyone tell me how to highlight (with color) the current link on a navigation bar, using css? I don't want to use the controller option. Here is the code from shared/menu.html.erb:

 <div id = "navigation">

  <ul>

  <li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li>
 <li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li>

 </ul>

 </div>

Solution

  • There are a few approaches to this, but if you're after a simple one, I suggest adding a class to your body.

    <body class="<%= params[:controller] %>_controller">
      ...
    </body>
    

    Then in your css you can do the following.

    body.menus_controller  #navigation a.menunav,
    body.drinks_controller #navigation a.drinknav {
      background-color : yellow
      color : blue
    }
    

    This can get complicated if you have multiple pages you want to split, but for this basic example it should be ok.