Styling Links: Part 2 of 2
Previously I wrote Styling Links: Part 1 of 2, where I talked about the three base states of a hyperlinks.
- The Placeholder state
- The Unvisited state
- The Visited state
So now let’s take a look at the expanded base states of a hyperlink:
/* Placeholder state */
a {
color: #111;
}
/* Unvisited state */
a:link {
color: blue;
}
/* Visited state */
a:visited {
color: purple;
}
/* State when the mouse cursor is over the link */
a:hover {
color: #f00;
}
/* Focus state (when tabbed to by the keyboard) */
a:focus {
color: #b00;
}
/* State when being clicked/pressed */
a:active {
color: #d00;
}
The order here matters
When styling your links, you should follow the above pseudo class ordering, otherwise styling may not occur as you had planned.
For instance, if a:active{}
comes before a:hover{}
in the cascade, you will never see the active state, as hovering will trump the active state.
But if the hover state comes before :active
, then on hover you will get the hover styling, and on press/click, the active styling will fire, even though you are still hovering
.
And here’s a quick fiddle demonstrating the necessity of placing :active
after :hover
.
Styling with attribute
Sticking with the basic styling of <a>
elements and their pseudo classes is the most common, as well as legacy browser friendly, way of styling links.
However, like other elements, hyperlinks can be styled by additional HTML attributes and their values.
Here are some examples to chew on:
a[title] {
/* Styles all links with a <b>title</b> attribute. */
}
a[target="_blank"] {
/*
Styles all links with a <b>target</b> attribute
that has a value of "_blank".
*/
}
a[role="button"] {
/*
Styles all links with a <b>aria <i>role</i></b> attribute
set to the value of "button". Potentially handy
if you're looking to cut down on multiple helper
classes on a single element.
*/
}
a[href^="https"] {
/*
Styles all links with a <b>href</b> attribute
that have urls that start with "https".
*/
}
a[href$=".com/"] {
/*
Styles all links with a <b>href</b> attribute
that have urls that end with ".com/".
*/
}
a[href*="google"] {
/*
Styles all links with a <b>href</b> attribute
that have urls that contain the string "google".
*/
}
A good use case for using some of the attribute selectors could be if you want give a visual cue to links that are secure a[href^="https"]
or links that will open the page in a new window a[target]
Wrap it up
The examples I showcased here are merely proof of concepts. I wouldn’t necessarily recommend having all these different styles of links on a website. But hopefully there are some use cases here that you weren’t aware of and hopefully they will be able to help you out down the road.