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

How Can I Style Current Page Links Differently with CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-14 04:25:11652browse

How Can I Style Current Page Links Differently with CSS?

Customizing Link Styles for the Current Page Using CSS

Often, web developers want to differentiate the appearance of links on the current page from others. One common approach is to swap the text and background colors.

To achieve this effect with CSS, consider the following approach:

li a {
  color: #A60500;
}

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

This code ensures that all links on the webpage have a red (#A60500) text color. When a user hovers over a link, its text color changes to black (#640200) and the background becomes black (#000000).

In the HTML, create a navigation menu with multiple links:

<ul>

Alternatively, you can use jQuery to dynamically add a class to the current page link:

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

This script iterates through all links on the page and adds the active class to the one that matches the current URL. CSS can then be used to style the active link differently, allowing you to customize the appearance of the current page link.

The above is the detailed content of How Can I Style Current Page Links Differently with CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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