CSS way of looping a background image with cover or contain sizing

Vandervals picture Vandervals · Jun 9, 2015 · Viewed 12k times · Source

Say you are trying to animate a tilable background like this:

As soon as you change the dimensions of the container, the looping animation breaks!

Is there any way to make this responsive without JS?

Answer

vals picture vals · Jun 9, 2015

The problem is that, to make it responsive, you need to set the animated background-position using percentages.

But, when you set background-size as cover or contain, in some cases the width is adjusted to 100%. In this case, background-position using percentages is useless (won't move it).

The only way that I have found to manage this is moving the image to a pseudo element, and moving it. To keep the continuity, though, we will need two pseudo elements.

But that won't work on a textarea.

You didn't said anything about textarea being a requirement, so I am posting this. To show that it works on resize, hover it.

.container {
  width: 160px;
  height: 100px;
  position: relative;
  border: solid 1px black;
  display: inline-block;
}
.container:nth-child(2) {
   width: 220px;  
}
.bg {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.bg:before, .bg:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    background-image: url(http://i.stack.imgur.com/wBHey.png);
    background-size: 100%;
    animation: move 2s infinite linear;
}

.bg:before {
    right: 100%;
}

@keyframes move {
    from {transform: translateX(  0%);}
      to {transform: translateX(100%);}
}
<div class="container">
  <div class="bg"></div>
</div>
<div class="container">
  <div class="bg"></div>
</div>

test image