Chief Technology Officer & Photographer | Irvine, CA

No Flicker All CSS Image Hover State Trick

I’m sure it’s already out there, but I just discovered it today, and figured I’d share my recently acquired knowledge…

With one client I’m working with, I’m forced to use image only nav’s on all their sites, but on hover states, I have always been getting that little “flicker” before showing the hover state image.  Well, that’s because the image has to load into the browser cache.  So my next thought was to just put in a JS image pre-loader – and step violently back in to the 90’s…grrr…but it “works”.  I have been searching for a better way to do it, and found it today!

Basically, you use 1 image for the image you are going to apply a hover state on, like this:

Make sure you setup your CSS to only show the top half of the image, and then on hover, set the background-position to a negative value to shift it.  For instance, on this item’s hover state, you’d set “background-position:0 -30px;”.

*EDIT* – Actually, instead of moving the background positioning by pixels, as of lately, I’ve really been just setting up the images so they are equal heights to take advantage of “background-position:top OR bottom;” accordingly as Martin suggested below.

This way…both of the “images” are loaded when the page is loaded, the hover state is just hidden until you put your cursor over it.  Thanks to the 3twenty3.com site’s code for helpin’ a brotha out!

AND…I just found a blog post about this here as well -> http://www.webdesignerwall.com/tutorials/advanced-css-menu/

Comments

  1. To simplify it even more, if the height of both “image states” is equal, you can simply do background-position: top; and background-position: bottom; for :hover state. I’ve been doing this for a while, you can also add an additional class for .active and add another “rollover” state to the image set. Then you can use top, middle, bottom. Used it in the main nav here: http://www.ylcc.com

  2. Andy Ferra says:

    You can put all of your navigation items into one image if you like and just offset it accordingly.

  3. Ann says:

    Thank you for sharing! The flickering when hovering css images was driving insane. I tried so many tricks that are shared on the web, but this is the only one that stops the flickering in both IE and FF.

  4. Samson says:

    This is great information. Thanks for sharing!

  5. Oneida says:

    Good post.

  6. Tom says:

    Thanks!

  7. jean says:

    thanks a lot! it helped and prevented my hovered image from flickering.

Leave a Reply to Martin Kulakowski Cancel reply

*