Tuesday, March 31, 2015

Remove hover from named anchors in HTML5

Top of this post - a named anchor with an unintended :hover effect.

I want :hover on links (anchors with a href attribute), but not on named links (anchors with a name attribute).

I use :hover to make links change color when the mouse hovers over them, for example, hover your mouse over this link: link to :hover on w3Schools. However, I also have named anchors on my site (e.g. <a name="top_of_post">Top of this post - etc ...</a>) so that I can link to parts of the page (e.g. click this link to go to the top of this post i.e. to my named anchor). Hover your mouse over the anchor above (at the top of this post - the text that says "Top of this post - etc ...") and you will see that it gets :hover as well, because it is an anchor tag.

Both of these use the anchor tag, but only one of them is an actual link. I want :hover on the links (<a href="http:/www...">) but not on the anchors (<a name="top_of_post">).

The page A:hover and named anchors has a fix for this. Create a CSS rule that will reverse :hover for anchor tags with a name attribute:

a:hover {text-decoration: underline; color: red; background: yellow}
a[name]:hover {text-decoration: inherit; color: inherit; background: inherit}

This works nicely, except that in HTML 5, the name attribute on anchor elements is marked as obsolete. It is recommended that you use the ID attribute instead of NAME. I could change that CSS rule to use a[id]:hover instead of a[name]:hover, but that presents a new problem. I will use ID in anchor tags for many reasons, not just to create named anchors. I certainly do not want to remove :hover effects from all anchor tags that I might give an ID to.

So, the fix I now use for HTML 5 is to create a class for named anchors. It isn't as nice because I have to modify my code, but at least I can easily do a global find all <a name=" and replace with <a class="namedAnchor" id=".

a:hover {text-decoration: underline; color: red; background: yellow}
a.namedAnchor {text-decoration: inherit; color: inherit; background: inherit}

And now I have named anchors with no :hover.

Bottom of this post - a named anchor with no :hover effect.