css: avoid image hover first time blinking

前端 未结 12 593
深忆病人
深忆病人 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:49

    This technique works nicely for me and ensures not only is the hover image pre-loaded, but it's also ready and waiting to be displayed. (Most other solutions rely on switching the background image on hover, which just seems to take the browser a bit of time to figure out, however much the image is pre-loaded.)

    Create :before and :after pseudo elements on the container with the two images, but hide the one you want to see on hover. Then, on hover, switch the visibility.

    So long as they both share the same size and positioning rules, you should see a neat swap.

    .image-container {
        &:before { display: block; background-image: url(uncovered.png); }
        &:after { display: none; background-image: url(uncovered.png); }
    }
    .image-container:hover {
        &:before { display: none; }
        &:after { display: block; }
    }
    

提交回复
热议问题