Adding style to your rel attributes with CSS

View the finished example: Adding style to your rel link.

There’s a little attribute in HTML links that is starting to get a bit of attention lately. The “rel” attribute is a sparsely defined attribute that applies some meta information about a link’s relationship to other documents. Unfortunately, this information is usually hidden from your users. Let’s take a light-hearted stab at turning it into a visual element.

Rel attribute usage

While the W3C originally considered the rel attribute to describe the relationship of pages to each other, i.e. next, previous, directory, and start. The attribute has been adopted by the Microformat community for its inherit usefulness. The rel attribute is now used for tags, to define your relationship to someone, and even to tell search engines not to bother following a link.

The opportunities to use the rel attribute are seemingly endless. There are more proposals to define people you don’t like and links for voting.

But all of this flexibility comes at a small price. To remain valid, you need to tell the browser what these new rel values may actually mean. This is handled by linking to appropriate profiles. Just simply insert the profiles into your head tag. Multiple profiles may throw a validation error, but it’s ok. You don’t need to do this for the standard rel values.



We will be using the CSS3 attribute selector functionality to look at the value of the rel attribute and apply some style accordingly. First we’ll add some padding and a background image to any link that has a rel attribute. We’ll then use background positioning to display an icon that is appropriate for the link. It’s a fairly simple hack.

For more information on using attribute selectors, check out my previous posts:

Sample HTML Code

  • This link is ignored by search engines (rel="no-follow")
  • (rel="tag")
  • Sample CSS


    a[rel] {padding-left:20px; background:url(rel-sprite.png) no-repeat 0 0; }
    a[rel~="help"] {background-position: 0 -350px ;}
    a[rel~="license"] {background-position: 0 -1347px ;}
    a[rel~="no-follow"] {background-position: 0 -1200px ;}
    a[rel~="tag"] {background-position: 0 -47px ;}

    It’s all fun and games

    I’ll be the first to admit this exercise has significant issues. I’m assuming the following elements are true:

    1. All possible rel attribute values are accounted for in my CSS, if not there will be a blank space generated by the first rule
    2. You can only have one relationship defined by XFN. Unfortunately, most people are defined by multiple values, i.e. rel=”met friend colleague”. This CSS does not account for multiple values.

    So, the display of your rel attributes may be a bit off in the edge cases. Keep the spirit light and nobody will say anything… I hope. Have fun with your rel attributes. They’re just sitting there waiting to be used.

    View the finished rel attribute style example.

    Related Information

    Progressive enhancement of links using the CSS attribute selector

    Attribute Selector Test Page

    We have avoided using CSS3 rules for too long. It’s been difficult to justify using rules that won’t work for a significant portion of our audience, Internet Explorer 7 and below. However, Internet Explorer 8 is coming out soon and does work with the features we like.

    I think it’s fairly safe to assume IE7 users will upgrade to IE8 within a short time. Those stuck with IE6 for one reason or another will slowly disappear as they are given new computers or their locked down environments are upgraded.

    So, with the future of CSS3 functionality within reach, I’ve been energized to begin experimenting again. I’ll be writing a series of blog posts over the next few months that look at CSS3 functionality as a progressive enhancement. How can we continue to deliver a perfectly fine web site to IE6 and IE7 and mobile phones while enhancing the functionality of more modern browsers and devices?

    Attribute Selectors

    CSS attribute selectors are the golden ring on the web development merry-go-round. They can be daunting to learn, addictive to use, but then disappointing when you realize they are out of your grasp when you test in Internet Explorer. We can, however, begin using them to add additional functionality based on your pre-existing, semantic code. Attribute selectors give you power to write CSS that pinpoints the stuff you already code, without having to go back and add classes or ids. I’ve written previously about using attribute selectors to let your users know the language of a site they are about to visit. This trick relies on the rarely used hreflang attribute, which identifies the language of the site targeted in a link.

    There are many other attributes in your HTML, from table headers, image src, link titles, and selected options. Think about all of those juicy attributes just waiting to be targeted. Also think about how you could actually do something useful with them.

    Announce the file type of a link with CSS

    I once worked for a company that had hundreds of thousands of static HTML pages in their intranet. With no content management system; it was impossible to make global changes. The only thing they shared was a common set of style sheets. Does this sound familiar? Follow along as we increase your site’s usability in a less than perfect, but efficient way.

    First off, for accessibility, you need to let users know when a link will open a file, what type it is, and how large it is. This is best done by adding it to your HTML code:


    Foo presentation (.pdf, 5kb)

    That delivers the information to everyone, regardless of their browser. This, however takes time and is a daunting task for updating legacy code.

    We can, however, use the atttribute selector to target the extension of the link to display the icon and insert the text describing the file type. Here’s the sample HTML code:


    It’s a simple list of links for different types of files. We’ll be looking at the extensions: .zip, .pdf, .doc, .exe, .png, and .mp3. Feel free to extend this list to any extension you so desire. This would be especially helpful for a company that uses proprietary file types within their intranet.

    Now, let’s look at the CSS:


    a[href$="zip"],
    a[href$="pdf"],
    a[href$="doc"],
    a[href$="exe"],
    a[href$="png"],
    a[href$="mp3"] {padding-left:20px; background:url(bg-file-icons.png) no-repeat 0 0;}
    a[href$="png"]{background-position: 0 -48px;}
    a[href$="pdf"] {background-position: 0 -99px;}
    a[href$="mp3"]{background-position: 0 -145px;}
    a[href$="doc"]{background-position: 0 -199px;}
    a[href$="exe"]{background-position: 0 -250px;}

    a[href$=".zip"]:after{content: "(.zip file)"; color:#999; margin-left:5px;}
    a[href$=".pdf"]:after{content: "(.pdf file)"; color:#999; margin-left:5px;}
    a[href$=".doc"]:after{content: "(.doc file)"; color:#999; margin-left:5px;}
    a[href$=".exe"]:after{content: "(.exe file)"; color:#999; margin-left:5px;}
    a[href$=".mp3"]:after{content: "(.mp3 file)"; color:#999; margin-left:5px;}
    a[href$=".png"]:after{content: "(.png file)"; color:#999; margin-left:5px;}
    a[href$=".exe"]:after{content: "(.exe file)"; color:#999; margin-left:5px;}

    See the final test page.

    Pattern matching in the attribute selector

    We have some limited “regular expression” functionality in CSS3. We can search for an attribute’s presence and match a pattern within the attribute’s value.
    Patrick Hunlon has a good summary of the pattern matching:

    • [foo] — Has an attribute named “foo”
    • [foo=”bar”] — Has an attribute named “foo” with a value of “bar” (“bar”)
    • [foo~=”bar”] — Value has the word “bar” in it somewhere (“blue bar stools”)
    • [foo^=”bar”] — Value begins with “bar” (“barstool”)
    • [foo$=”bar”] — Value ends with “bar” (“I was at the bar”)
    • [foo*=”bar”] — Value has bar somewhere (“I was looking for barstools”)

    Attach icons to anything with CSS

    The CSS is simply looking to see if the desired extension is at the end of the link href. If so, apply the following styles.

    Adding an icon to the link

    First, we are match any of the desired file extensions. We then add a background image and some padding on the left side with a bulk rule. Then the background position on the sprite is adjust for each particular link type. Combining multiple icons into one background image reduces the number of files the user has to download, making your page faster. This will work with any browser that recognizes attribute selectors, including Internet Explorer 7. However, support for more obscure attributes may be spotty.

    There’s another peculiarity with pattern matching. Some attributes are case sensitive while others are not. The href attribute is NOT case sensitive, so the above rules will also work if your image name was FOO.ZIP, foo.Zip, or foo.zip.

    Adding the descriptive text

    Now, we are going to add a bit of descriptive text to each link. We can’t describe the file size, but we can tell the user what type of file it is. This is using the :after(content:) functionality and is supported by Internet Explorer 8 (yeah!!!) but not Internet Explorer 7 and below (boo!!!).
    We will also adjust the color and give it a bit of spacing.

    A big step forward with a small chunk of work

    There you have it. A small chunk of CSS coding has now added substantial usability to your legacy pages. While the CSS version is not as accessible as having the data in the actual link code, it’s a significant improvement over nothing at all. Further, there’s no harmful effect on browsers that do not understand the function. You’ve added information, but haven’t taken anything away. This is a win in my book. To save some time and effort, you could just download and use this package of CSS and icons from Alexander Kaiser.

    This rather simple example of attribute selectors and pattern matching can open your eyes to many possibilities. There are a number of developers that have been expoloring this potential for the past few years. Take a look at some of these resources for more ideas and have some fun.

    Image sprites – flexible and accessible packages

    User generated ratings and reviews are an important part of all Yahoo! sites. You can find them on just about every page of Yahoo! Tech.  It was important for us to develop a ratings presentation device that was easy to code, accessible, flexible, and as light-weight as possible. Our final design uses a combination of image sprites and negative text-indent to satisfy these requirements.

    Product ratings are represented with 1 to 5 stars. Other sites have used inline images; repeating a solid or empty version for each of the five stars. stars image from Yahoo! ShoppingOther sites, such as Yahoo! Shopping, have used a single inline image representing the number of stars.  At best, the image will have an alt attribute that descibes the number of stars. However, the content is locked inside the image. This is an easy approach for coding but isn’t the most accessible approach.

    Yahoo! Tech uses the content first approach to design

    Content-first design improves accessibility. This approach places the relevant content in semantic markup. It then uses CSS to transform that content into the visual design. Here is a sample rating from Yahoo! Tech: Overall:4/5, Quality:5/5, Support: 3/5. Our CSS transform that simple text into a series of stars and accompanying text. User testing with a screen-reader user led us to remove visual descriptions from the content, i.e."stars" or "bars".

    With the content in the page, it was time to look at the visual design.

    Ratings are presented in either an unordered list or definition list. We need to place descriptive text in front of the stars and want the stars to be aligned with each other. These considerations lead to using spans with a combination of CSS rules to hide the text, insert a background image, and absolutely position the ratings to the right side of the list item. Let’s look at the code.

    The HTML – span

    To use a background image for the stars, we need a container that can be manipulated with CSS and not include presentational behaviors of its own. This is why we use the span, a generic inline container. We could use a strong or em, but feel the span offers the best versatility. You never know when the graphic designer will ask for some text to be bolded or emphasized in the same list item.

    Sample code for a rating

    • Overall: 4/5

    The span’s title will generate a tooltip when the user places their mouse over the rating (not Internet Explorer). Screen readers’ default settings ignore title attributes on non-form items.

    The CSS

    Spans are inline elements.  To display background images, we need to make them display block, define a height, width, and move the text off the screen. To keep them inline with the text, we are also positioning them absolutely. We could position them relatively or floated the spans. Position absolute works the best for our pages.The parent list item is positioned relatively to give the span a contextual anchor. Negative text-indent will hide the rating text.


    .ratingslist {list-style-type:none;}
    .ratingslist li {position:relative; padding:3px 5px; }
    .ratingslist li span {text-indent:-1000em; width:66px; display:block; position:absolute; top:5px; right:20px;}

    Image sprites display the desired number of stars

    The list item is given a class with a number at the end (stars8). This will display an image with four out of five red stars. We are using a scale of 0 to 10 to accomodate half stars. To display other rating variations, we change the modifier, i.e. prostars4, retstars4, bars4, bigstars4, etc…

    To simplify the maintenance of the site and reduce server requests; Yahoo! Tech also uses image sprites. Sprites are single images that include multiple icons with a consistent spacing between them. Use background positioning to display the desired chunk of the image. Each sprite represents the possible color variations used on the site: red, blue, and green. Minimizing the color palettes reduces the final image size. For more information on sprites, read CSS Sprites: Image Slicing’s Kiss of Death by Dave Shea. As a further enhancement, alpha transparent png images are used for most browsers and index-transparent gifs are presented in the Internet Explorer 6 style sheets. 

    Background images are positioned with the set of numbers after "no repeat." The horizontal positioning is first. Our sprite is vertical, so we are leaving it alone, hence the 0 value. The vertical positiong comes next. If we want to display 2 out of 5 stars, we need to shift the background down to that part of the image (-530px). Here is the CSS for presenting the specific star variant.


    /* Ratings images
    ======================================= */
    .stars0 span {background:url(/images/bg-ratings.png) no-repeat 0 -650px;}
    .stars1 span {background:url(/images/bg-ratings.png) no-repeat 0 -620px;}
    .stars2 span {background:url(/images/bg-ratings.png) no-repeat 0 -590px;}
    .stars3 span {background:url(/images/bg-ratings.png) no-repeat 0 -560px;}
    .stars4 span {background:url(/images/bg-ratings.png) no-repeat 0 -530px;}
    .stars5 span {background:url(/images/bg-ratings.png) no-repeat 0 -500px;}
    … (repeated for each variation of the stars and bars)

    This approach has allowed the Yahoo! Tech engineers to maintain a consistent presentation with minimal markup. For pages that need special tweaks we can easily adjust the positioning by using descending selectors:


    #mytech .ratingslist li span { right:5px;}

    Caveats

    We’ve only found a few small issues with this approach.

    • You cannot count on background images being displayed on the printed page. Our print style sheet removes the text-indent and background images to display “Overall: 4/5”.
    • When someone includes more than 4 products in the comparison table, the text of some rating parameters will begin to overlap the stars. If they were inline images or if we floated the spans, they may drop to the next line.

    Yahoo Tech! ratings are another example of creating accessible and visually dynamic pages by considering the underlying content structure before attacking the styles. Users of all abilities are presented with solid information. That’s how you can deliver a 5 star page every time.

    Related Information

    IE7 background sprite bug – the saga continues

    I’ve been able to narrow down my problem with IE7b2 and background sprites. However, I still have not been able to create a stripped down test page that consistently mis-behaves. So my observations, while not scientific, could save you some hours of debugging.

    Internet Explorer 7beta2 is not treating transparent png background images correctly. It sees “background-position: 0 0” as “background-position: 0 100%”. Come to think of it, I have only tried a vertical sprite, this may be the same for a horizontal sprite.

    What’s the solution?

    You could create a series of rules in your IE7 style sheet to measure your new sprites from the bottom up, instead of top down. But this doesn’t solve some of the other odd issues with IE7 and transparent png images. I’ve seen the images load upside down and I’ve seen the images move when you scroll the page and the image hits the bottom of the browser. I thought I was going crazy or that I had some sort of mutated version. But this pseudo-animation works on other computers.

    Our IE6 style sheet replaces our pretty alpha transparent png graphics with a simpler index transparent gif version. We replaced our re-measured rules in the IE7 with this set and it has solved our problems. It would be great to take advantage of IE7’s ability to use alpha transparent png images, but this bug is just driving me nuts. I’ve also been in contact with the IE7 team. They are dedicated to building the best browser possible within their constraints and hopefully this will be figured out before the final launch of IE7.

    One other note of advice. Creating alpha transparent png images via the save as command in Photoshop on a Mac gave us the worst results. Those images did some very funky things on the page. Fireworks created better images.

    c’est fini!

    I don’t know if it is official or not, but I can say that the Microsoft engineers are interested in what developers have to say and have worked on this bug. I believe it has been fixed and will be all good to go with the final release of IE7. I can’t confirm or deny this, but I am pleased with their response to my initial post and followup.This bug has officially been officially fixed as of Release Candidate 1 and you can use your transparent png sprites without a worry in the world!

    IE7 passes the sprite test

    beegee sprite thumb
    I came across an issue with Internet Explorer 7 beta displaying the rating stars incorrectly in Yahoo! Tech. After doing some testing, I realized the browser was measuring the sprite image from the bottom up, rather than the top down. This is a significant issue. I had to create a new set of rules in the IE7 style sheet for the new measurements.

    I use sprites extensively. I love the way they save server requests and I think they are much easier to maintain. The thought of fixing all of my sprites was enough to send me downstairs for another coffee. But I noticed the only sprites being affected were the ratings. I needed to find what was special about these. The ratings sprites use a span that is absolutely positioned in either an unordered list or definition list. This gives us flexibility for displaying them across the site.

    IE7 Does it Right!

    I created a test page for using sprites. I stripped the CSS down to simple list handling, floating, positioning, and sprite. IE7 handled it perfectly. I even replaced the links with spans and that still didn’t trip up IE7. Take a look at the test page , IE7 Sprite Test, to see the results. While I’m still having problems with IE7’s handling of sprites. I believe it is a unique combination of styles that is causing this issue. I don’t think the average person will need to worry about this.

    When I do figure out what is going on with Yahoo! Tech’s rating sprites, I’ll update this blog with the solution. For more information on using sprites, visit Dave Shea’s article CSS Sprites: Image Slicing’s Kiss of Death on A List Apart.