css: avoid image hover first time blinking

Haradzieniec picture Haradzieniec · Nov 8, 2012 · Viewed 42.1k times · Source

I have an anchor that changes its background image when hovered with a class class-btn that contains a background-image.

When hovered, it has

a.class-btn:hover
{
    background-image('path/to/image-hovered.jpg');
}

When the page loads the first time and you hover this button the first time, it blinks (it takes about half a second to download the hovered image). How to avoid that blinking without JavaScript (only simple css and html is allowed)?

I tried to search Stack Overflow for the similar question, but with no luck.

Just added:

  • Should I "preload" the hovered image? How?
  • Should I play with z-index or opacity?

It happens with all browsers and thus the solution should work for all browsers.

Answer

Kristian Svensson picture Kristian Svensson · Jul 6, 2015

Here is a simple and effective css image preloading technique I have used several times. You can load several images by placing content: url() url() url()... etc.

body:after{
 display:none;
 content: url(path/to/image-hovered.jpg) url(path/to/another-image-hovered.jpg);
}