Styling Links With CSS The Right Way

Styling Links With CSS The Right Way

Today I got stuck while figuring out while styling links for a theme. I was trying to figure out how to style the regular links, visited links and hovered links. But the catch is that if you have a named anchor within a heading, it gets text-decoration and link color which is not desirable. For example this code:

<h1>Business <a name="hello">systems that solve</a> your entrepreneurial challenges</h1>

Looks like this:

The problem is—it’s a named anchor. There’s no reason it should stand out for any accessibility reasons. Then the frustration began. anchors, links, visited, hovered—ideally you should be able to target each of these with CSS. And here’s the selector discovery.

A few points:

  • a:—The anchor tag
  • :link—Elements that have an href attribute
  • :visited—Visited style.
  • :hover—Hover style of elements with an href attribute

Here’s the catch—Now you may think why not use :link:visited? Apparently it doesn’t work. :link is implied when you use :visited because obviously you can’t visit elements that do not have an href attribute. But you can do :visited:hover because it does make sense. Anyways, it you come across this issue here’s the code.

/* elements with href attribute when hovered. Keep the transition to see the states it goes through upon hovering*/
:link { color: #c00; transition: all 0.5s linear; }

/* elements with href attribute when visited Note: :visited means links that have been visited. Obviously you can't visit links without href attribute */
:visited {color: #080}
/* elements with href attribute when hovered */
:link:hover { color: #fc0; }
/* visited elements with href attribute when hovered */
:visited:hover { color: #fc0; }

Generally you’ll never need :visited:hover.

References: How To Remember The Order of Selectors
Thanks to @justintadlock

Divi WordPress Theme