CSS selector for anchor element using document fragment
While the :target
pseudo-class exists for matching a named anchor or an element with an ID corresponding to the current URL fragment, CSS does not provide a selector for matching links that point to the current URL fragment.
There is no clean way to do this without JavaScript. I would heavily prefer using JavaScript over polluting the markup with unsemantic elements and invalid attributes for the sake of accommodating CSS (section
elements cannot have name
attributes).
The hashchange
event is well-supported, so if you can afford it it's simply a matter of listening for that event and toggling a class on the right element:
var navLinks = document.querySelectorAll('nav > a');
window.onhashchange = function() {
for (var i = 0; i < navLinks.length; i++) {
if (navLinks[i].href.match(/(#.*)/)[1] == window.location.hash) {
navLinks[i].className = 'selected';
} else {
navLinks[i].className = '';
}
}
};
var navLinks = document.querySelectorAll('nav > a');
window.onhashchange = function() {
for (var i = 0; i < navLinks.length; i++) {
if (navLinks[i].href.match(/(#.*)/)[1] == window.location.hash) {
navLinks[i].className = 'selected';
} else {
navLinks[i].className = '';
}
}
};
section {
background: #fff;
}
section:target {
background: #f00;
}
a.selected {
font-weight: bold;
}
<nav>
<a href="#s1">First Section</a>
<a href="#s2">Section 2</a>
</nav>
<main>
<section id="s1">
<p>Example paragraph
<p>Paragraph 2
</section>
<section id="s2">
<p>Example paragraph
<p>Paragraph 2
</section>
</main>