Monday, May 31, 2010

Pure CSS Image Rollover Workaround

Rollover effects are when an element on a page changes somehow when you hover your mouse over it. These effects are incredibly common, but unfortunately are almost always Javascript based. The reason for this, until quite recently, has been that there was no alternative; the only way to accomplish a rollover effect was to use javascript. The advent of CSS, however, has changed this. More specifically, the :hover attribute is what is to thank here. Say that we wanted an image rollover. Before CSS, the only way would be to use javascript:


HTML/CSS
<img src='somepic.jpg' alt='somepic' onmouseover="javascript:this.src='anotherpic.jpg';" />


With css, however, we could now do this:


HTML/CSS
<style>
img:hover {
background-image: url('somepic.jpg');
}
</style>
<img src='somepic.jpg' alt='somepic' />


The problem, like with most CSS-fixes, was with Internet Explorer 6. A significant portion of internet users still use IE 6, so it is neccesary to find a workaround. Internet Explorer 6 only recognizes :hover on link tags (<a></a>). The answer lies, then, in using said tag for the purpose we want. Now, in general, you don't set width and height attributes (or background images) to links, but "don't" doesn't mean "can't". So, let us set up the html for the rollover effect:


HTML/CSS
<a href='#' class='rolloverlink' ></a>


So, what exactly did we just do there? First off, we pointed the link at '#', meaning that clicking it will only return the same page. Second, we applied the class 'rolloverlink' to it. Now, we must define the 'rolloverlink' class.


HTML/CSS
<style>
.rolloverlink {
cursor: default;
display: block;
width: 100px;
height: 100px;
background: url('somepic.jpg');
}
.rolloverlink:hover {
background: url('anotherpic.jpg');
}
</style>


Since we want our link to act effectively like an image, we had to apply some attributes to it. First off, we keep the cursor from changing when we hover the mouse over it. To do this, we set cursor: default;. Next, we want our link to behave like a block-level element, similarly to a div or paragraph tag. To do this, we set display: block;. At this point, we could set a background image--however, we won't. The reason is that since the link now functions like a div tag (and not like an image tag), it won't automatically expand to the size of the image, so we have to set the size manually. Lastly, we set the background image. This should be self-explanatory. Then, to make it a rollover, we do the same thing that we did before, which is add a :hover and set the background image to something else.