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
Release: 2024-12-14 04:25:11
Original
651 people have browsed it

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

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

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

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!

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