How To Style The Current Page Differently In The Main Navigation?
Solution 1:
A simple way to do it without using javascript or php etc would be to add a different class to the body tag on each page.
<body class="nav-1-on">
Then in your css file:
body.nav-1-ona.nav-1, body.nav-2-ona.nav-2 { color:red )
SO you need XXX classes for however many nav items you have and you put a class on each nav item too as illustrated.
Make sense?
Solution 2:
Update (brain fade, had wrong selector). For CSS3 browsers, you can easily target the page name itself:
a[href*=pageNameImOn.htm] {color: red;}
The *=
will here match all href paths that include pageNameImOn.htm
in them, which would match:
<ahref="/my/path/to/file/pageNameImOn.htm"><ahref="/pageNameImOn.htm"><ahref="/pageNameImOn.htm#interalJumpLink">
Solution 3:
For the link that you want to be a different color, you can manually set the style
<a style="color:red">My link is red</a>
Probably a better way to do would be to define a class where the color is red
<style> .visited { color:red } </style>
and then for the actual link
<a class="visited">My red link</a>
Solution 4:
This solution uses jQuery, jQuery is just a compiled code library for javascript really, offering easy to use snippets and functionalities.
The is definitely the easiest way of achieving what you're after, although it is "client-side" so the class will be added by the users machine, rather than being added by the server and then sent to the user. But for smaller sites, it should suffice.
What is happening: This code finds your navigation, here it is looking for the li
of .nav
, so replace ('.nav li
') with whatever your menu class is called, so possibly: ('.mymenu li')
. It then sees if the menu link matches the current page, if it does, it adds a class to the li. So you also need to create a class of .active
, such as: .active{background-color:blue;}
Hope this helps!
<scripttype="text/javascript"charset="utf-8">
$(document).ready(function() {
jQuery('.nav li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).addClass('active');
}
});
});
</script>
Solution 5:
Just for the fun of it.
What about a Single page
and CSS3
only solution, without any backend code or Javascript:
<ul><li><aid="home"href="#home">Home</a></li><li><aid="terms"href="#terms">Terms of use</a></li></ul>
CSS
lia { color: black; }
#home:target { color: red; }
#terms:target { color: red; }
The :target
selector in CSS will match an ID selector that matches the current hash-tag.
Here's some more information: http://reference.sitepoint.com/css/pseudoclass-target
Pretty good support in Firefox, Safari, Opera and Chrome.
Incomplete support in IE9 and IE10:
IE doesn’t react to the Back and Forward buttons: the element doesn’t apply or remove the pseudo-class at all. http://www.quirksmode.org/css/contents.html
Post a Comment for "How To Style The Current Page Differently In The Main Navigation?"