Make the active tab stand out in the navigation menu

Could you please advise on how to highlight the active tab in a menu when users switch to another page? This is my current code:

.nav {
    float: left;
    font-size: 125%;
}
.nav ul {
    margin: 0;
}
.nav li {
    background: none repeat scroll 0 0 #777777;
    display: block;
    float: left;
    margin-right: 7px;
}
**.nav .youarehere {
    background: none repeat scroll 0 0 #FF9900;
}**
.youarehere a {
    color: #FFFFFF;
}
.nav li:hover {
    background-color: #FF9900;
}
.nav a {
    color: #FFFFFF;
    display: block;
    padding: 6px 12px;
    text-decoration: none;
}

I would appreciate any suggestions on how to enhance this functionality.

The menu structure looks like this:

<ul class="nav">

                      <li> <a href="{$smarty.const._URL}/index.{$smarty.const._FEXT}" class="wide-nav-link menu_link" >{$lang.homepage}</a></li> 
                      <li class="dropdown">
                        <a href="#" class="dropdown-toggle wide-nav-link menu_link " data-toggle="dropdown">{$lang.category} <b class="caret"></b></a>
                        <ul class="dropdown-menu menu_link">
                        {dropdown_menu_video_categories}
                        </ul>
                      </li>

                      {if $smarty.const._MOD_ARTICLE == 1}
                      <li class="dropdown">
                        <a href="#" class="dropdown-toggle wide-nav-link menu_link " data-toggle="dropdown">{$lang.articles} <b class="caret"></b></a>
                        <ul class="dropdown-menu menu_link">
                        {dropdown_menu_article_categories}
                        </ul>
                      </li>
                      {/if}
                      <li> <a href="{$smarty.const._URL}/topvideos.{$smarty.const._FEXT}" class="wide-nav-link menu_link ">{$lang.top_videos}</a></li>
                      <li><a href="{$smarty.const._URL}/newvideos.{$smarty.const._FEXT}" class="wide-nav-link menu_link">{$lang.new_videos}</a></li>
                      <li><a href="{$smarty.const._URL}/randomizer.php" rel="nofollow" class="wide-nav-link menu_link">{$lang.random_video}</a></li>
                      {if isset($mm_menu_always_inject1)}{$mm_menu_always_inject1}{/if}     
                      <li><a href="{$smarty.const._URL}/contact_us.{$smarty.const._FEXT}" class="wide-nav-link menu_link">{$lang.contact_us}</a></li>

                                            {if isset($mm_menu_always_inject2)}{$mm_menu_always_inject2}{/if}       
                      {if $logged_in != 1 && isset($mm_menu_notlogged_inject)}{$mm_menu_notlogged_inject}{/if}
                    </ul>

Answer №1

One option is to dynamically add the "active" (or selected) class to the currently selected menu item and apply the following style:


.nav li a.active {
    color: #FFFFFF;
}

@ChrisHerbert's solution may not be effective as it could change all menu items due to the class being applied to the body tag. (EDIT: Solution has been updated, refer to comments)

With @ChrisHerbert's answer, you have two options:
1) Use Javascript to target the specific menu item based on its index relative to the body tag. (Non-Javascript alternatives can be explored)
OR
2) Utilize CSS selectors like .home .nav li:nth-child(0) {}, .about-us .nav:nth-child(1) {}, etc. if you are aware of each page's index in the menu. Be cautious with older versions of IE when using child selectors!

It is advisable to implement this solution without relying on the body tag. However, having the class on the body can still be beneficial for adding page-specific styles.

Answer №2

Assign a distinct class to the <body> tag for each individual page. For instance, on the homepage:

<body class="home">

For the contact page: <body class="contact">

As for the blog page: <body class="blog">

...and so forth.

Subsequently, in your CSS, implement something along these lines:

.home .nav li.home, .contact .nav li.contact, .blog .nav li.blog {
  // apply styles to show active state
} 

Answer №3

When considering how to approach this task, the key question is whether you want the functionality to be dynamic or if you are manually coding each page. While the existing solutions are effective, they may be excessive if you are only dealing with individual pages. One simple solution would be to apply a class to the relevant navigation element based on the current page. This method is straightforward for beginners but @ChrisHerbert's approach offers a more elegant way to achieve dynamic styling using just CSS without the need for PHP conditionals.

HTML

<div class="nav">
<a href="home">Home</a>
<a href="about-us">About us</a>
<a href="portfolio" class="selected">Portfolio</a>
</div>

CSS

.nav a {
color:#ff4444;
}
.nav a.selected {
color:#ff44ff;
}

UPDATE: On further review, I see that @AnnieCaron's response aligns closely with my own viewpoint.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue arises when CSS selectors do not function properly with absolutely positioned divs

I am experiencing an issue with my CSS code that is functional on CodePen but not on my actual website. I am attempting to target the .appraisals class for manipulating the background color of an opaque screen slider containing information. Despite using a ...

How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code. http://embed.plnkr.co/fSIm8B/script.js I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q To make it more functional, how can I pass a variable to the service? Here is the broken ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...

Designing a webpage compatible across different browsers that features an image positioned relatively over two rows of a table

I am working on creating a unique table layout for a web page that resembles the design linked below: Click here to view the image http://kelostrada.pl/upload/test.png Your assistance in achieving this would be greatly appreciated. Currently, I have imp ...

Discovering repeated arrays within an array

Given a nested array, what is the best approach to finding duplicates efficiently? var array = [ [ 11.31866455078125, 44.53836644772605 ], [ // <-- Here's the duplicate 11.31866455078125, 44.53836644772605 ...

JavaScript - Swapping out element in object array

I'm struggling to develop a function that can normalize features within a dataset, ensuring they fall between 0 and 1. My goal is to iterate through all the features and update their values as I perform normalization. While the normalization process i ...

Converting Base64 data from a canvas to a blob and then processing it in PHP

I encountered a problem when trying to send a base64 image from a canvas to PHP using an AJAX POST request. After doing some research on the internet, I discovered that some people suggested increasing the memory_limit in the PHP server settings, possibly ...

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

Is there a way to search for a sequence of bytes within a file and then substitute them with a different buffer of data?

In my current project, I am working with NodeJS to read files using the fs.readFile method which returns a buffer of the file contents. My goal is to identify a specific pattern of bytes within this buffer and replace them with either a new buffer of the ...

Run JavaScript Function from Within

Apologies for the straightforward question, but I'm struggling to find an answer anywhere. As a complete JavaScript beginner with no experience, I'm at a loss. Currently, I have a function linked to a simple button click: <input type="button ...

Shifting and implementing various styles across numerous elements at the same time

There is an anchor tag containing two spans... <a class="banner-logo" href="/search"><span id="banner-logo-hello">Hello</span><span id="banner-logo-world">World</span></a> When hovering over the anchor tag, I want to c ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

What is the most efficient way to switch between different views in AngularJS while preserving the data in the views'

Every time I navigate from page1.html to page2.html in AngularJS and then return back to page1.html, my page model data disappears. Can someone please help me figure out how to preserve this data? I've looked at other questions on this topic but coul ...

Centering Tabs in React-Bootstrap

By default, Bootstrap-react's tabs align to the left. <Tabs defaultActiveKey={2} id="uncontrolled-tab-example"> <Tab eventKey={1} title="Tab 1"> Tab 1 content </Tab> <Tab eventKey={2} title="Tab ...

Using a <button> tag instead of a <div> inside of a <button> is not allowed, as clickable divs are typically frowned upon. What

I'm currently developing a React App that functions as a calendar, allowing users to click on specific days displayed as large squares to view information for that day. For accessibility purposes, I initially considered using <button> elements b ...

Localized Error: The property 'clientWidth' cannot be retrieved as the object is null or undefined

The issue with the error message seems to only occur on Internet Explorer, and unfortunately there doesn't seem to be a clear solution at the moment. Even after setting http-equiv="X-UA-Compatible" to IE8, the problem persists and I cannot seem to re ...

Retrieve the element that was clicked during the show.bs.collapse event in Bootstrap 4's Collapse feature

Looking for a solution to dynamically inject data into a collapsing panel based on the element that triggered it? I need to capture the clicked element when the panel is about to be displayed. Here is the HTML structure: <div class='container&apos ...

Troubleshooting AJAX Problems in ASP.NET and C#

I am currently working on implementing a WebMethod call in my C# code behind using AJAX. I have a Bootstrap Modal that should be displayed when a linkbutton is clicked, triggering the execution of the WebMethod through AJAX to populate a table in the modal ...

Issues with voice state updates in JavaScript

I am currently working on setting up a discord bot to send notifications when someone joins a voice chat. While coding in Atom, I encountered the following error: TypeError: Cannot read property 'send' of undefined at Client.client.on (C:\U ...

Performance rating - Displaying the overall rating

http://jsfiddle.net/q8P7Y/ I am currently facing an issue with displaying the final score at the end of a project. There are multiple approaches I can take to solve this problem, but I am unsure of the best way to proceed. In my current setup, the next b ...