Home > Web Front-end > JS Tutorial > How to Style Current Page Links in CSS?

How to Style Current Page Links in CSS?

DDD
Release: 2024-10-20 11:50:30
Original
240 people have browsed it

How to Style Current Page Links in CSS?

Styling Current Page Links in CSS: A Comprehensive Guide

Often, designers seek to enhance the user experience by distinguishing the current page's link from others, highlighting its active status. One effective approach to achieve this is through CSS, offering flexibility and easy customization.

To alter the appearance of the current page's link, CSS provides a simple yet powerful solution:

<code class="css">a:active {
  color: #A60500;
  background-color: #000000;
}</code>
Copy after login

With this code, links that are currently active will display with a reddish-brown text color against a black background. This visual differentiation helps users navigate the site more intuitively.

For more advanced modifications, jQuery offers even greater control. By leveraging the .each function, you can iterate through all links and dynamically apply the active class to the link matching the current page's URL:

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

This code ensures that the active class is only added to the link that corresponds to the current page, regardless of the page structure or specific URLs used.

To further refine the selection of links, consider using more specific selectors, such as $("nav [href]") if your links are located within a navigation element. Additionally, if your URLs contain parameters, you may need to strip them before comparing URLs to account for these variations.

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

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template