Skip over navigation

Deconstructing a CSS Hover State

By on Apr 10, 2009 in Tutorials, Web Design, Web Engineering

Designers, when producing your web designs, it’s important to remember that it’s often more efficient to use CSS and a customized graphic rather than javascript for common effects like button rollovers.

Javascript based rollovers require more overhead because the browser must download two images (rather than one) and must process javascript to trigger the effect every time, whereas with the pure CSS approach, one image is stored in the browser’s cache as well as the style/behavior. This shaves time off of the overall download speed of your website and in this game every second counts!

As I’ll illustrate here, your original artwork will likely need to be broken out into a discrete and customizable graphic to take advantage of the CSS rollover.

As my example, I chose the hover effect of the “Register Now” buttons on this site: http://www.marklogic.com/UserConference2009/

Rather than use two separate images with some javascript to swap in the “over” state image on a mouse event (the mouse rolling over the button), I instead used one image and CSS positioning to “slide” the over state into place. This works because the anchor tag is defined in CSS as only as wide (via padding) as one button and therefore the over state is visible only when it slides into view. Imagine looking into your camera viewfinder as a train goes by directly in front of you. Only the train cars that fit into the width of the viewfinder would become visible as they “slide” into view. Make sense?

Here is a screenshot of the discrete button image document I made to achieve the desired rollover:
hoverButtons.png

Here is the html for this button:

<div class="registerNowButton">
	<a href="#"></a>
</div>

Here is the CSS that controls the over state behavior:

.registerNowButton a {
	padding: 16px 99px 18px 79px;
	background: url(images/buttonRegisterNow2009.gif) no-repeat 0 0;
	float: left;
	position: relative;
	left: 100px;
	bottom: 14px;
}

.registerNowButton a:hover {
	background-position: -178px 0;
}

Fortunately for me, the layered button graphic was semantically named, so the whole process was made that much simpler. No guesswork whatsoever. I looked at the layers, knew what they all meant and therefore knew what to make visible to achieve the desired look for each state. Yay CSS! Yay semantics!

Hey! This wasn't written by a troop of baboons! It was written by , who does awesome work at Loud Dog, a digital branding firm in San Francisco that helps businesses express themselves authentically via identities, websites, and marketing collateral.

If you want us to do awesome work for you, if you have a question, or if you're just feeling lonely and want to chat, we want to hear from you!

Get in touch

Leave a Reply

Your email address will not be published. Required fields are marked *