css: avoid image hover first time blinking

前端 未结 12 591
深忆病人
深忆病人 2020-12-07 19:52

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

When hovered, it

相关标签:
12条回答
  • 2020-12-07 20:23

    Just change the size of the background image, instead of the source of it! So...

    a.class-btn {
        background-image: url('path/to/image-hovered.jpg');
        background-size: 0;
    }
    a.class-btn:hover {
        background-size: auto;
    }
    
    0 讨论(0)
  • 2020-12-07 20:24

    If they are the same dimensions, one possibility is to draw the two images directly on top of each other, with the CSS :hover class for the top image having display: none;

    This way both images will be preloaded, but hovering will make the second visible.

    0 讨论(0)
  • 2020-12-07 20:25

    The best way to do this is to just insert the images onto the webpage and set display to none.

    0 讨论(0)
  • 2020-12-07 20:27

    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.

    0 讨论(0)
  • 2020-12-07 20:29

    @Kristian's method of applying hidden 'content: url()' after the body didn't seem to work in Firefox 48.0 (OS X).

    However, changing "display: none;" to something like:

    body:after {
     position: absolute; overflow: hidden; left: -50000px;
     content: url(/path/to/picture-1.jpg) url(/path/to/picture-2.jpg);
    }
    

    ... did the trick for me. Perhaps Firefox won't load hidden images, or maybe it's related to rendering(?).

    0 讨论(0)
  • 2020-12-07 20:31

    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);
    }
    
    0 讨论(0)
提交回复
热议问题