CSS style for links pointing to current page?

I was wondering if there is any way in CSS3 for link styles that point to the same page that are already displayed in the browser, for example, to highlight it in red in the navigation telling the user "You are here right now!" as I have few link lists, and I expect some users to probably read them one at a time.

So, if the browser is in /features/feature3.php , then obviously I would like to change the look of all links with the same href address.

It seems that there is only :hover :focus and :active , but nothing can solve this problem exclusively in CSS. Did I miss something?

+6
source share
3 answers

you can use CSS3 attribute selectors for this.

 a[href='your url'] { *** } 
+4
source

Try this example , good enough.

 <ul id="navlist"> <li><a href="index.html" id="homenav">Home</a></li> <li><a href="products.html" id="prodnav">Products</a></li> <li><a href="faq.html" id="faqnav">FAQ</a></li> <li><a href="contact.html" id="connav">contact us</a></li> </ul> <body id="home"> body#home a#homenav, body#products a#prodnav, body#faq a#faqnav, body#contact a#connav { color: #fff; background: #930; } 
0
source

Therefore, CSS does not support this function directly. So you need to look for alternatives and weigh compromises.

Use JavaScript and jQuery to add a class

 $(function () { $('a[href="' + document.location.pathname + '"]').addClass("current"); }); 

Then you can create your styles around the .current selector.

 a.current {background-color: white;} 

Just do not put class="current" in your HTML - let everything be fine when the page loads, and javascript will add the class to the correct elements. This is good because it will work on any page and does not require dynamic code on the server. Of course, this can be done without jQuery. This may require adjusting the query string parameters, absolute URLs, and several other edge cases, but is great for a simple case.

Use server side dynamic code to put class = "current" in the appropriate elements

You could do it the same way, but it will not be as concise and expressive as the JavaScript version, because most server-side software environments do not have DOM selectors available.

0
source

Source: https://habr.com/ru/post/906820/


All Articles