Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: avoid image hover first time blinking

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.

like image 451
Haradzieniec Avatar asked Nov 08 '12 10:11

Haradzieniec


3 Answers

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');
}
like image 119
Kristian Svensson Avatar answered Nov 19 '22 00:11

Kristian Svensson


The easiest way to avoid this is to make use of image sprites. For a good overview, check out this CSS Tricks article.

That way, you not only solve the flicker problem you're seeing, but will also reduce the number of HTTP requests. Your CSS will look something like:

a.class-btn { background: url('path/to/image.jpg') 0 0 no-repeat; }
a.class-btn:hover { background-position: 0 -40px; }

The specifics will depend on your images. You can also make use of an online sprite generator to make the process easier.

like image 21
CherryFlavourPez Avatar answered Nov 19 '22 01:11

CherryFlavourPez


A simple trick I use is to double up the original background image making sure to put the hovered image first

.next {
  background: url(../images/next-hover.png) center center no-repeat;
  background: url(../images/next.png) center center no-repeat;
    &:hover{
      background: url(../images/next-hover.png) center center no-repeat;
    }
 }

No performance hit and very simple

Or if you're not using SCSS yet:

.next {
  background: url(../images/next-hover.png) center center no-repeat;
  background: url(../images/next.png) center center no-repeat;        
 }
 .next:hover{
  background: url(../images/next-hover.png) center center no-repeat;
 }
like image 15
Callam Avatar answered Nov 19 '22 01:11

Callam