How to Style Links According to Link Type

Using CSS, it’s pretty easy to style a whole bunch of different elements of the same element type in different ways by assigning them different classes. However, if you want to get technical, this can also be achieved by using attribute selectors. Attribute selectors are used in CSS to select different HTML elements to style based on their inline HTML attributes. This tutorial is about using those attribute selectors to select and style anchor tags based on the type of file you’re linking to.

Let’s say you have the following anchor tags:

Join us in our newest publication:
<a href="http://www.facebook.com">Facebook</a>
<a href="mailto:[email protected]">Email Me</a>

And you want to style each anchor tag differently — maybe you’d like the text of the Facebook link to be blue, and you’d like the “Email Me” text to be italic. Like we said earlier, you could style them differently by assigning different classes to each element, OR you could do it using attribute selectors, like this:

a[href^="http://"]{
    color: blue;
}
a[href^="mailto:"]{
    font-style: italic;
}

As you can probably gather, the syntax is relatively straightforward here. The elements you’re looking to select are followed by brackets that indicate their attribute values, written out like [href^=”value”]. Using these attribute selectors, you can quickly and easily style your anchor tags according to the types of files that they link to.

There is one exception to the syntax above. If you’re looking to single out an anchor tag that links to a pdf file, your CSS selector would need to look like the code snippet below. For this example, let’s say we wanted to make the font bigger:

a[href$=".pdf"]{
     font-size: 25px;
}

The syntax here changes only slightly — you replace the “^” symbol from the first examples with the dollar sign: “$”. Also note that you’re singling out the attribute by the .pdf extension, rather than what comes at the beginning of the link.

Share and Enjoy !

0Shares
0 0