Home >Web Front-end >CSS Tutorial >How Can I Style Current Page Links Differently Using CSS and JavaScript?
Highlight Current Page Links with CSS
Question:
How can I alter the styling of links on the current page to distinguish them from others? Specifically, I want to swap the text and background colors.
CSS Solution:
li a { color: #A60500; } li a:hover { color: #640200; background-color: #000000; }
Example:
<ul>
JavaScript Solution:
To automatically apply the active styling, you can use jQuery's .each function:
$(document).ready(function() { $("[href]").each(function() { if (this.href == window.location.href) { $(this).addClass("active"); } }); });
Considerations:
<ul>if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
This approach eliminates the need to manually modify each page and ensures consistent styling across different page URLs.
The above is the detailed content of How Can I Style Current Page Links Differently Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!