Search code examples
htmlcssbackground-positionbackground-size

CSS background-position animation not working


I have a background image that I want to continuously scroll from right to left. I want the image to cover the entire screen, but when I set background-size: cover; it does not animate at all. How can I fix this?

HTML

<body>
  ...
</body>

CSS

body {
  background-color: rgb(15, 5, 40);
  background-image: url('./images/star background.png');
  background-repeat: repeat;
  background-position: top left;
  background-size: cover;
  animation: myMove 3s linear infinite;
}

@keyframes myMove {
  from { background-position-x: right; }

  to { background-position-x: left }
}

If I set background-size #px #px; or initial or X% Y% then it works fine, but doesn't cover the whole screen? Also, here is the image: enter image description here


Solution

  • Here is another idea using translate on pseudo element where you make the element big to have enough room for an infinite movement:

    html::before {
      content:"";
      position:fixed;
      top:0;
      left:0; /* change to right for the opposite direction */
      bottom:0;
      width:200%;
      background:url(https://i.sstatic.net/wJKLc.png) 0/50% auto;
      animation:move 2s linear infinite;
    }
    
    @keyframes move {
      to {transform:translateX(-50%);} /* change to "50%" for the opposite direction */
    }