Stop Background Images Flickering On Hover State
How do I stop the flicker when people hover over my links’ background image?
A Typical Scenario
You have a logo/picture link that you want the background to change when the mouse hovers over it. Simple, you might think; using CSS, specify one background image for the ‘unhovered state’ and a separate background image for the ‘hover’ state. Something like this:
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" href="style.css" /> <title>Stop Background Images Flickering!</title> </head> <body> <h1>My Wonderful Heading Text</h1> <a href="#" title="#">My Background Image Link</a> </body> </html> |
style.css
1 2 3 4 5 6 7 8 9 10 | a { display:block; text-indent:-5000px; width:298px; height:99px; background: url(myimage.jpg) 0 0 no-repeat; } a:hover { background: url(myotherimage.jpg); } |
Nothing wrong with this you might think but this method means that the browser needs to load two images. The real problem lies in the fact that the second image (myotherimage.jpg) isn’t loaded until the mouse is hovered over the link, causing the flicker the first time you hover over it (after which it is cached by the browser)
The Solution
The trick is to use only one image for the background image. This single image is an amalgamation of the two images used previously. We then use background positioning to change the image on the ‘hover’ state.
style.css
1 2 3 4 5 6 7 8 9 10 | a { display:block; text-indent:-5000px; width:298px; height:99px; background: url(myimage.jpg) 0 -99px no-repeat; } a:hover { background: url(myimage.jpg) 0 0; } |
Example:
With Flicker
Without Flicker
This technique is nothing new. It is coined as CSS Sprites and has been around for a long time but it is surprising how many people don’t use it. Just think of your poor site visitors who don’t have mega fast broadband and imagine the size/delay of their flicker!
Not something you want on your website really. A good example is daily.co.uk, the domain name registrar (I have quite a few with them). Hover over any of their site’s buttons for the first time and it’s mega-flicker-tastic!
Other Posts You Might Like :)
2 Responses to “Stop Background Images Flickering On Hover State”
Leave a Comment


No need to do this. Just preload the second image in html with the display:none property.
@Meiling
I don’t see the benefit there.
What can be easier than a few lines of css?