1

I have the below CSS / SCSS code:

I've set the background properties in the figure and only changed the background-size property for the hover... but it just jumps to the new size instantly instead of animating smoothly.

Can anyone see why the transition isn't working?

If I set the original background size as 100% then it works however

SCSS:

figure {
    position: relative;
    background-size: cover;
    background-position: center;
    aspect-ratio: 8 / 5;
    overflow: hidden;
    transition: background-size 0.4s ease;

    &:hover {
        background-size: 120%;
    }
}

HTML

<figure style="background-image: url('loremipsum.jpg')"></figure>

1 Answer 1

3

The background-size property is not used for smooth transitions; browsers typically don't handle it well. That's why when changing from cover to 120%, the background image updates without animation.

Instead of trying to animate background-size, place the background image inside the element as a separate block, using an img, and animate that block with transform: scale().

transform is fully animatable and works smoothly.

CSS:

figure {
    position: relative;
    aspect-ratio: 8 / 5;
    overflow: hidden;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.4s ease;
        display: block;
    }

    &:hover img {
        transform: scale(1.2);
    }
}

HTML:

<figure>
    <img src="loremipsum.jpg" alt="">
</figure>

The figure sets the size of the space and clips anything that goes beyond it using overflow: hidden.

The img fills 100% of the width/height of the and uses object-fit: cover to behave like a background that fully covers the area.

When hovering over the figure, the image smoothly zooms in thanks to transform: scale(1.2).

So, to sum up: you should remove the background image from the figure and place the image inside it using an img tag. Keep the figure with overflow: hidden and set the image's width and height to 100%, with object-fit: cover, so it fills everything without distortion. Then add a transition on the image for the transform property, and on the figure hover, apply transform: scale(1.2) to the image. This way, when you hover, the image will zoom smoothly because transform is animatable, unlike the background-size you were using before.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.