Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Set style to current link in a Navigation Bar with CSS
To set a style to the current link in a navigation bar, you need to add an active class to the current page link and define CSS styles for it. This helps users identify which page they are currently viewing.
Syntax
.active {
background-color: color;
color: text-color;
/* other styling properties */
}
Example
The following example demonstrates how to style the current link in a navigation bar −
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #333;
overflow: hidden;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 20px;
text-decoration: none;
transition: background-color 0.3s;
}
li a:hover {
background-color: #555;
}
.active {
background-color: #4CAF50;
color: white;
}
.active:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#company" class="active">Company</a></li>
<li><a href="#product">Product</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</body>
</html>
A horizontal navigation bar appears with a dark background. The "Company" link is highlighted in green, indicating it's the current page. Other links are white and turn gray when hovered over.
Key Points
- Add the
class="active"attribute to the current page link in your HTML - Define the
.activeclass in CSS with distinctive styling (different background color, text color, etc.) - Include hover effects for the active state to maintain interactivity
- Use
transitionproperties for smooth color changes
Conclusion
Styling the current link with the .active class provides clear visual feedback to users about their current location in your website. This improves user experience and navigation clarity.
Advertisements
