Sunday, 13 April 2008

Use CSS not JavaScript for rollovers!

Why use Javascript for your rollovers when simple CSS will do? I prefer CSS over Javascript because it degrades better in non-compatible browsers in comparison to JavaScript and it's so straight forward to implement in CSS, just take a peek below...

CSS rollover example in action:

CSS rollover code:

<style type="text/css">
 display: block;
 width: 50px;
 height: 50px;
 text-decoration: none;
 background: url('');
 background-position: -50px 0;
<a class="rollover" href="#">7lt;span class="hidden">Hidden Text</span></a>

Key points about the example

The image used is made up of two images; this is often referred to as a CSS sprite. Having just one image is better than two because you've halved the number of requests needed to retrieve the images, resulting in better site performance. Initially, the first 50×50 pixels of the image is shown (CSS element a.rollover). Then when we activate the rollover with the mouse the CSS element a.rollover:hover is activated, which moves the background image left by 50 pixels this results in a different image being output.

To counteract the loss of text value for the link because images are used (text in links is used by search engine crawlers and screen readers), we have a span that contains text - but the span text is hidden using the display:none; CSS attribute.


There is a great article with some more advanced examples by Dave Shea called CSS Sprites: Image Slicing's Kiss of Death which you should check out.


Anonymous said...

Great idea to use the hidden span - i was thinking about removing my rollovers for SEO reasons until i saw this!

TKS Concepts said...

Definitely an awesome idea using a hidden span! It was a very helpful idea for a frustrated designer. :P

Lking said...

Hi there, sounds prity cool, can you give me a better idea of how to do this in blogger?