Image rollovers have been around since the days of the Flying Toasters, but back then it took some moderate skill in JavaScript to get them to work. If you had a copy of Dreamweaver, it could spit out the code for you. Now with CSS3 doing a simple image rollover with a link is easy using only HTML and a little CSS3. There are other CSS3 tricks in the same vein, but I’ll save those for a different tutorial.
With any rollover, you need two images, or an image with two parts. You’ll need the initial state of the image and a rollover state. This tutorial uses separate images, instead of combining the two states into one image and transitioning the position when a user hovers over the graphic. I’ll be putting links on the images, but it would be easy to take this code and create your own set of rollovers without links.
I’ve made a simple set of buttons that are icons in their initial state. The hover state versions use a faded background of the same icon with a dark text overlay that explains what the icon means.
First, to keep things neat and portable, I create a div that wraps around the buttons (I call them tabs in this naming convention). Next I make a class for the individual divs that contain the tabs. This class defines the dimensions and margins. Make the dimensions identical to your graphics and use your margins to give them breathing room. These same divs will have ids so that you can define individual background images that coordinate with the initial images. These are the background images that will show when you rollover the images inside the divs. The CSS transition you’ll see is the top image fading in opacity, revealing the background image behind it when you hover over the div. Now let’s get to the code…
CSS
.tab_wrapper {
width:730px;
height:110px;
}
.top_tab {
width:100px;
height:100px;
float:left;
margin:5px 35px 20px;
}
#agriculture {
background:url(http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/farm_icon_over.png) no-repeat;
}
#economic {
background:url(http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/money_icon_over.png) no-repeat;
}
#quality {
background:url(http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/home_icon_over.png) no-repeat;
}
.top_tab a img {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;-o-transition:
opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.top_tab a:hover img {
opacity:.01;
}
.clear {
clear:both;
}
HTML
<div class=”tab_wrapper”>
<div class=”top_tab” id=”agriculture”><a href=”#”><img src=”http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/farm_icon.png” /></a></div>
<div class=”top_tab” id=”economic”><a href=”#”><img src=”http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/money_icon.png” /></a></div>
<div class=”top_tab” id=”quality”><a href=”#”><img src=”http://cdn2.hubspot.net/hubfs/395217/Images/BLOG/rollovers/home_icon.png” /></a></div>
<div class=”clear”></div>
</div>