How to create rollovers in CSS without JavaScript?

CSS coding allows developers to write web friendly code for their clients. Its best to stray away from the old methods of HTML with rollover images using JavaScript as that never produces clean optimized code. The old style OnMouseOut and OnMouseOver functions in JavaScript should be discarded in favor of a clean CSS look and feel.

CSS rollovers are quite easy to implement as they use only CSS and your HTML knowledge. Where images are concerned, it’s best to keep in mind that you should only use them for the top-level navigation part of your menus. Use text in CSS for the menu items with CSS powering the rollover effect and you will notice a much faster loading page. So use this tutorial only for the top-level menu bar to compliment a side menu; I can also cover CSS drop-downs in another tutorial.

To avoid pages that are slow to open, CSS does replace JavaScript as the better choice. Using just one image is better than a JavaScript file that preloads images for different states – that slows the page loading time.

Let’s look at a CSS rollover. You can edit it as needed in your web editor. The image for the example can be downloaded here. Note the design, the button is drawn twice. This is due to the CSS code and how it will manage the rollover. The CSS below displaces the image position in order to show the second half of the image as the rollover image. This way, you only need one image for the effect. Ensure that the size of one of the buttons (half the image width) matches the values in the a.mouseover CSS code below.

<title>How to create rollovers in CSS without JavaScript?</title>
<style type=”text/css”>
/* set the height and width values here, ensure the values match half the image size */
a.mouseover {
display: block;
width: 175px;
height: 67px;
text-decoration: none;
background: url(“cssrollover2.gif”);
/* when the mouse rolls over the image, it is displaced by the button length giving the effect of a rollover change – ensure the value in pixels matches the image i.e. same as above width */ 
a.mouseover:hover {
background-position: -175px 0;
.displace {
position: absolute;
left: -5000px;
/* Note the use of text on the hyperlink in case of a non-CSS compliant page */
<a href=”#” mce_href=”#” class=”mouseover” title=”CSS Rollovers”><span class=”displace”>Buy Now!</span></a>

The CSS rollover style button above uses overlay text for the image being used. The <span> tag allows the text to be displayed if CSS is not supported.

Always find a CSS solution and your code will be sharper, cleaner and result in faster loading pages.

Leave a comment