user3314853 user3314853 - 5 months ago 14
CSS Question

Preventing image flicker on hover when replacing it with another image (CSS)

When I hover my cursor on the logo the first time after the page loads, it starts to blink rapidly for about a second.
I've thought about using sprites, but I don't want to set the logo as the background image - I already have one. Here's my CSS code:

html {
-webkit-background-size: 100%;
-moz-background-size: 100%;
-o-background-size: 100%;
background-size: 100%;
-webkit-filter: brightness(0.6);
-moz-filter: brightness(0.6);
-o-filter: brightness(0.6);
-ms-filter: brightness(0.6);


#logo {
position: fixed;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;


content: url('logobeforehover.png');
<div id="logo">
<img src="logoafterhover.png"/>


There will always be some flicker, since the user's browser will have to load the image from the server. TCP & HTTP have some amount of overhead, and the fastest you can reasonably expect (even for very small images) is about 100-200ms. Which is often noticeable. In reality, the time is often higher.

Possible solutions:

  • Place the image in the page somewhere, but don't display it. Setting display: none is often used, but that doesn't seem reliable anymore; alternatively, you can add an image with a width & height of 1px and z-index of -1. IMHO this is ugly. Note that this also increases initial page load.
  • Don't use CSS, but Javascript to switch the image. This way you can pre-load the image, and change it when it's loaded & ready, for example:

    var img = new Image();
    img.onload = function() {
        $('#logo').attr('src', $(this).attr('src'));
    img.src = ''
  • Use a CSS sprite, you already mentioned you don't want to do that, but I'll list it for completion's sake. IMHO, it is the best solution.