CSS: styling file types

One of the greatest features added by CSS3 to the CSS specifications is the ability to select elements based on the presence of a substring in their attribute values. For that reason, we can actually stylize link elements whose URL points to a particular file type. To accomplish this task, we'll use the CSS3 attribute selector that matches the end of a string inside an attribute's value. Its syntax is: element[attr$="value"]. For example, consider the case of a list of links that contains some references to various file types, like so:

 <li><a href="foo.pdf">PDF file</a></li>
 <li><a href="foo.html">HTML file</a></li>

The href attribute of each link ends with a file extension (in this case .pdf and .html. We can take advantage of this fact and write the following CSS rules:

a[href$=".pdf"] {
 color: maroon;
 background: url(css-styling-file-types/pdf.gif) no-repeat 0 0;
 line-height: 2.5;

a[href$=".html"] {
 color: navy;
 background: url(css-styling-file-types/html.gif) no-repeat 0 0;
 line-height: 2.5;

These rules instruct supporting browsers (including IE7 and later versions) to select only the links whose href attribute ends with the specified strings. You can see an example here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.