sptaule
sptaule

Reputation: 39

How to infinite zoom in and out smoothly with background image in CSS

The background image isn't smooth when it comes to animate it (some kind of blink) and I can't make it zoom from the image center.

This is for my personnal website I'm trying to make.

    *{margin: 0;padding: 0;}

    body
    {
        background-color: #0C090A;
        background-image: url(../abstract-bg.png);
        animation: zoom 30s infinite;
            -webkit-animation: zoom 30s infinite;
    }

    @keyframes zoom {
        0% {
          background-size: 100%;
        }
        50% {
          background-size: 105%;
        }
        100% {
         background-size: 100%;
        }
      } 

I would like to get the background image (which is 1920*1080) zoom slowly to 105% of it's original size (or something like that), and then go back to 100%. Also, if it's possible, make it zoom from the center, and not the top left corner. Thanks for those who can help.

Upvotes: 0

Views: 4684

Answers (2)

user7148391
user7148391

Reputation:

It's choppy because the animation duration is too long for 5% of the width of the image. either increase the size or decrease the duration of the animation or use a bigger image.

Or you can use scale() which make use of the GPU i believe, However this time we won't be using the image as a background.

body{
  overflow-x:hidden; 
}
img {
  transform-origin: center center;
  animation: zoom 30s infinite;
  max-width: 100%;
}

@keyframes zoom {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
    /* equals 105% */
  }
  100% {
    transform: scale(1);
  }
}
<img src="https://picsum.photos/id/238/1920/1080">

Upvotes: 0

Hazem Nabil
Hazem Nabil

Reputation: 161

yes of course you can :) just add

  background-position:center center;
  background-repeat:no-repeat;

in the body css and add

html{
  height: 100%;
}

full css code:

* {
  margin: 0;
  padding: 0;
}
html {
  height: 100%;
}
body {
  background-color: #0C090A;
  background-image: url(https://images.pexels.com/photos/556416/pexels-photo-556416.jpeg);
  animation: zoom 30s infinite;
  -webkit-animation: zoom 30s infinite;

  background-position: center center;
  background-repeat: no-repeat;

}

@keyframes zoom {
  0% {
    background-size: 100%;

  }
  50% {
    background-size: 150%;
  }
  100% {
    background-size: 100%;
  }
}

you can test the code: https://playcode.io/358401

Upvotes: 1

Related Questions