Home > Web Front-end > CSS Tutorial > How Can I Style Current Page Links Differently Using CSS and jQuery?

How Can I Style Current Page Links Differently Using CSS and jQuery?

Mary-Kate Olsen
Release: 2024-12-14 18:58:11
Original
417 people have browsed it

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;
}
Copy after login

Example

Consider the following HTML structure:

<ul>
Copy after login

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");
        }
    });
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template