NotWork
NotWork

Reputation: 11

Why my animation does not work?

I Want the motion to work, but the background image position is fixed and does not move, why ?

@-webkit-keyframes anima {
    from {
        background-position: left;
    } to {
      background-position: right;
    }
}


#bando {
    border-radius: 4px;
    background-image: url(neon.jpg);
    background-size: 120%;
    width: 600px;
    padding-top:40px;
    padding-bottom:40px;
    margin-bottom: 10px;
    font-size: 30px;
    height:200px;
    animation-name: anima;
    animation-duration: 3s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    animation-direction: alternate;
}

Thanks for helping

Upvotes: 1

Views: 47

Answers (1)

Asons
Asons

Reputation: 87303

For this to work, make sure the image is bigger (or smaller) than the element, like in below sample, where the element is 600px wide and the image 800px

@-webkit-keyframes anima {
  from {
    background-position: left;
  }
  to {
    background-position: right;
  }
}

div {
  border-radius: 4px;
  background-size: 120%;
  background: url(http://lorempixel.com/800/280/nature/1/);
  width: 600px;
  padding-top: 40px;
  padding-bottom: 40px;
  margin-bottom: 10px;
  font-size: 30px;
  height: 200px;
  animation-name: anima;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-direction: alternate;
}
<div></div>


Another option is to use a pseudo element, as with that you can use transform to move the image, which I recommend and is a far more smoother and efficient way to do it

div {
  position: relative;
  border-radius: 4px;
  width: 600px;
  padding-top: 40px;
  padding-bottom: 40px;
  margin-bottom: 10px;
  font-size: 30px;
  height: 200px;
  overflow: hidden;
}
div::after {
  content: '';
  position: absolute;
  border-radius: 4px;
  background-size: 120%;
  background: url(http://lorempixel.com/800/280/nature/1/);
  width: 800px;
  height: 100%;
  animation-name: anima;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-direction: alternate;
}

@-webkit-keyframes anima {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-200px);
  }
}
<div></div>

Upvotes: 1

Related Questions