Many organizations have a lot of non-HTML document files. Word docs, PDF files, Excel spreadsheets, Powerpoint presentations, and the list goes on.
This can be an annoying experience if the link surprisingly opens an Excel spreadsheet when the user didn’t expect that. And it’s even more obtrusive if they are browsing on a mobile device and this happens.
The solution
What we need to do is dynamically display the file type next to all such hyperlinks using CSS. We could manually insert text for this, but a dynamically inserted icon is a better solution. In the past this method has been called link markers, or CSS cues, but basically they are just file type indicators.
First, lets write some HTML for the various hyperlinks.
<p><a href="http://www.google.com" target="_blank">new window</a></p>
<p><a href="http://www.google.com">external site</a></p>
<p><a href="mailto:mike@donotreply.com">mailto: link</a></p>
<p><a href="file.pdf">pdf files</a></p>
<p><a href="file.doc">word documents</a></p>
<p><a href="file.xls">excel files</a></p>
Each of these links are just the very basic code that you would need to insert a hyperlink.
No classes are needed because CSS can select each of these links using sub-string matching attribute selectors, demonstrated below. We are only interested in the file name at the end of the URLs.
a[href $=".pdf"] {
padding-right: 18px;
background: transparent url('images/icons/pdf.gif') center right no-repeat;
}
a[href $=".xls"] {
padding-right: 18px;
background: transparent url('images/icons/xls.gif') center right no-repeat;
}
a[href $=".doc"] {
padding-right: 18px;
background: transparent url('images/icons/doc.gif') center right no-repeat;
}
a[href ^="http://"] {
padding-right: 20px;
background: transparent url('images/icons/external.gif') center right no-repeat;
}
a[href ^="mailto:"] {
padding-right: 20px;
background: transparent url('images/icons/mailto.gif') top right no-repeat;
}
a[target="_blank"] {
padding-right: 18px;
background: transparent url('images/icons/newwin.gif') center right no-repeat;
}
The CSS code above basically detects the file extension at the end of the hyperlink in HTML, and adds just enough padding on the right side of the link to display a small background image icon that indicates the type of file before they click on it.
You can download a code sample right here.
The dollar sign ($) indicates the end of the string, and the upwards pointing arrow (^) indicates the beginning of a string.
You can also modify this CSS code (using media queries) so that it only displays these icons on mobile devices.