Highlighting the current page in a navigation bar is a common practice to provide visual feedback to users about their location within a website. Here's a step-by-step guide on how to highlight the current page in a navigation bar using CSS:
HTML Structure:
Typically, navigation menus are structured using unordered lists (<ul>
) with list items (<li>
) containing anchor tags (<a>
).
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="services.html">Services</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
Add a Class for the Current Page:
When generating the navigation bar (either manually or dynamically), add a class (e.g., active
) to the <a>
tag of the current page.
<nav>
<ul>
<li><a href="index.html" class="active">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="services.html">Services</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
In the example above, the "Home" link has the active
class, indicating that it's the current page.
CSS Styling:
Define the styles for the active
class in your CSS to visually distinguish the current page link from the others.
/* Basic styling for all navigation links */
nav a {
text-decoration: none;
color: #333;
padding: 5px 10px;
margin: 0 5px;
}
/* Highlighting the active link */
nav a.active {
color: #fff;
background-color: #007BFF; /* Change to your preferred highlight color */
border-radius: 4px;
}
In the CSS above, the active link is styled with a different color and background color to make it stand out.
Dynamic Highlighting (Optional):
If your website uses a server-side language or a CMS, you can programmatically set the active
class based on the current page or route. This way, you don't have to manually set the active
class for each page.
By following these steps, you can effectively highlight the current page in a navigation bar using CSS.