Home >Web Front-end >CSS Tutorial >How Can I Style Current Page Links Differently Using CSS and jQuery?
CSS Link Styling for Current Page
In the realm of web design, styling links can often be a crucial aspect for enhancing user experience and website aesthetics. If you seek to differentiate the appearance of links for the current page from others, CSS offers a straightforward solution.
Implementation with CSS
Adding the following CSS rules will allow you to swap the text and background colors for links on the current page:
li a { color: #A60500; } li a:hover { color: #640200; background-color: #000000; }
Example
Consider the following HTML structure:
<ul>
With the CSS rules applied, the link for the current page (e.g., "/programming.php") will have the text and background colors swapped when the page loads or the user hovers over it.
Dynamic Styling with jQuery
If you prefer a more dynamic approach, jQuery provides the following code to achieve similar results:
$(document).ready(function() { $("[href]").each(function() { if (this.href == window.location.href) { $(this).addClass("active"); } }); });
This code iterates through all links on the page and adds an "active" class to the link that matches the current URL. You can then use CSS to style the "active" class as desired.
By leveraging these techniques, you can effortlessly change the appearance of links for the current page, improving both the visual appeal and user experience of your website.
The above is the detailed content of How Can I Style Current Page Links Differently Using CSS and jQuery?. For more information, please follow other related articles on the PHP Chinese website!