Search code examples
htmlcsscss-transitionsimage-scaling

Scaling image with CSS Transition


This is how I want to scale my images, smoothly without any jumps.

My attempt does not work like in the gallery above, the image (red square in my case) jumps, my code:

section {
    background-color: rgba(0, 0, 0, 0.701961);
    width: 400px;
    height: 400px;
}

div {
    position: absolute;
    top: 120px;
    left: 120px;
    width: 160px;
    height: 160px;
    background-color: red;
    -webkit-transition: all .2s ease-in-out;

}

div:hover {
    -webkit-transform: scale(1.8);
}
<section>
    <div></div>
</section>

How to fix this? The red square jumps. Is it possible to scale smoothly with CSS Transition at all like in the gallery in the link at the beginning?


Solution

  • What do you mean by "jumps"? Try this, jumps too?

    section {
        background-color: rgba(0, 0, 0, 0.701961);
        width: 400px;
        height: 400px;
    }
    
    div {
        position: absolute;
        top: 120px;
        left: 120px;
        width: 160px;
        height: 160px;
        background-color: red;
        -webkit-transition: -webkit-transform 0.4s;
        transition: transform 0.4s;
    }
    
        div:hover {
            -webkit-transform: scale(1.8) rotate(0.01deg);
            transform: scale(1.8) rotate(0.01deg);
        }
    <section>
        <div></div>
    </section>

    Also, you could try the variant with a container for an image (like in the first link of your question).

    JSFiddle

    .banner {
        position: relative;
        z-index: 1;
        cursor: pointer;
        border: 1px solid #dfe2e5;
        background: #000;
        width: 310px;
        height: 150px;
        -webkit-transition: border-color 0.1s;
        transition: border-color 0.1s;
        overflow: hidden;
    }
    
        .banner:hover {
            border-color: #bdc1c5;
        }
    
        .banner__image-container {
            overflow: hidden;
            height: 100%;
        }
    
        .banner__image {
            -webkit-transition: all 0.4s;
            transition: all 0.4s;
        }
    
            .banner:hover .banner__image {
                -webkit-transform: scale(1.15) rotate(0.01deg);
                transform: scale(1.15) rotate(0.01deg);
                opacity: 0.5;
            }
    <div class="banner">
        <div class="banner__image-container">
            <img class="banner__image" src="https://picsum.photos/310/150/?image=1022"/>
        </div>
    </div>