CSS3 crossfade bg image when cover is used

2019-09-05 08:33发布

问题:

I am trying to animate/crossfade bg image using CSS3. I know that this works, but only in Chrome for now:

.image {
    width: 100%;
    height: 100%;
    background-size: cover;
    transition: background-image .5s ease-in;
    background-image: url(../image.jpg);
}

.image:hover {
    background-image:url(../image1.jpg;
}

In Chrome this works nicely, with seamless transition from one image to another. I know that I can animate background-position property using CSS3 keyframes and sprite image, but the problem is that I must use cover property. If I know exact dimensions of my holder div, then changing background position with keyframes works like a charm, but when adding background-size:cover in the mix, well, the only thing I can say that the results are not as expected.

Are there any workaround for this?

回答1:

You can set the second image on a pseudo element, and just change the opacity of that to make the hover effect

.test {
    position: relative;
    width: 450px;
    height: 300px;
    background-image: url(http://placekitten.com/300/200);
    background-size: cover;
}


.test:after {
    content: "";
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    background-image: url(http://placekitten.com/600/400);
    background-size: cover;
    -webkit-transition: opacity 1s;
    -moz-transition: opacity 1s;
    transition: opacity 1s;
    opacity: 0;
}

.test:hover:after {
    opacity: 1;
}

fiddle

By the way, this works cross-browser also