How to Make an Icon With Hover Effect Using Only CSS

I worked out a technique to give button images a hover or mouseover effect using only CSS. It’s probably been done before, but I think it’s useful enough to merit documentation.

For this example, let’s use the dashboard icon standard and hover images from my previous post. You’ll also need a 16×16 transparent image, blank.png (transparent png). The need for this blank image will become evident in a moment.

Here’s the HTML:

<a href="..." class="dashboardLink">
<img src="blank.png">

Note that we’ve used the transparent blank.png to fill the image tag. On some browsers, if there’s no content, the box element for the tag will not be rendered. Also, most browsers will render the content of the alt attribute as a tooltip on mouseover, so that’s a nice side effect of using an img to fill the space.

Now, here’s the CSS:

a.dashboardLink {
background: url(dashboard.png) no-repeat top center;
width: 16px;
height: 16px;
display: inline-block;
vertical-align: text-bottom;

a.dashboardLink:hover {
background: url(dashboard-hover.png) no-repeat top center;

a.dashboardLink img {
border: 0 none;
width: 16px;
height: 16px;

We’re displaying the dashboard.png image as the background of the content of the link tag. The a.dashboardLink:hover class supplies the alternate dashboard-hover.png image on mouseover. Setting a fixed height and width ensures that the element will be rendered in its full size, not clipped to height of other elements in the same box. display: inline-block is also necessary to ensure that the element height won’t be clipped in Firefox. vertical-align: text-bottom forces the image to align with any text in the same block (e.g., a menu bar), also in Firefox.

Regrettably, won’t permit me to put a style tag in this post, so I can’t show you the final effect.

Now, if only I can find a way to declare a pseudo-class inline, instead of in a style tag in the header – I’d like to subclass the Grails GSP link tag to generate hover buttons from just an image name and a URL. Has anyone had any luck finding a way to do that?


#css, #hover, #mouseover-effect