Friday, April 9, 2010

CSS rollovers

There are a few tricks I've found along the way that in CSS that have helped me out to a great degree. One of these tricks is the CSS button roll over. You can find different versions of this all over the web, but after using this for over a two years, I believe I've tweaked it so that it is the most SEO and browser friendly version. This is how it works:

You create the button image with both the static and rollOver state on the same image like below.


The static state of the button is on top. This image is 100x50. That means that your button will actually be 100x25. What we're going to do is simply show only the top half of the button. When a user rolls over the button, we'll only show the bottom half. What this does is eliminate the need for Java Script to load images for the roll over state.

Here's the CSS:

.btn_black a {
width:100px;
height:25px;
float:left;
text-indent:-2000px;
background:url(../images/css_rollover_btn.jpg) 0 0;
}

.btn_black a:hover {
background:url(../images/css_rollover_btn.jpg) 0 -25px;
}

I've created a Class called "btn_black" for the button. As explained before, the width and height are defined as 100x25. The button is set to "float:left;" I've fond that setting the button to a float state solves cross-browser issues.

The text-indent is there for SEO purposes. When using images as buttons, you want to still have text involved so that the Search Engines can better read the link. In this case, it takes the text you'll write as the link, and shoves it -2000 px off screen.

Finally we set the button as an image. You'll notice the "0 0" after the URL in the background. This is setting the coordinates of the image shown. Next when there's a roll over (a:hover) we move the image up by 25px with "0 -25px".

Now you need to have it placed in HTML. We'll set it to go to a homepage:

<div class="btn_black"><a href="http://www.blogger.com/index.html" title="black button">HOME</a></div>

All this does is create a DIV tag with the Class of our button. The link inside points to our home, and the text "HOME" is there for the Search Engines, but pushed off screen by 2000 px.

That's the simple CSS roll over button. You can also remove the words "button" from the image and remove the "text-indent" from the CSS. This would allow the text to be on top of the button. Either way would work, and I recommend doing it that way if what you want fits this. Often though we want more from our buttons that just simple text on top of them.

No comments:

Post a Comment