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

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

Linda Hamilton
Release: 2024-12-15 17:59:10
Original
642 people have browsed it

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

Styling the Current Page Link Differently with CSS

When navigating through a website, visually distinguishing the current page from others enhances the user experience. This article explores a CSS solution to change the link color for the currently active page.

Consider the following HTML structure:

<ul>
Copy after login

To begin, we'll use CSS to style all links:

li a {
  color: #A60500;
}

li a:hover {
  color: #640200;
  background-color: #000000;
}
Copy after login

Now, let's address the CSS for the current page link. Using jQuery, we can iterate through all links and check if their href attribute matches the current page's URL:

$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});
Copy after login

With that addition, links that point to the current page will receive the "active" class. We can then enhance the CSS to change the link color for elements with that class:

.active {
  color: #FFEE00;
}
Copy after login

However, it's important to note the following considerations:

<ul>
  • Depending on the page structure, narrowing down the link selection may be necessary.
  • If URL parameters are used, stripping them might be required to ensure accurate matching.
  • The above is the detailed content of How Can I Style the Current Page Link 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