用封面或包含大小调整循环背景图像的CSS方式

Van*_*als 33 css css3 css-animations responsive-design

假设你试图为这样的tilable背景设置动画:

.container {
  width: 160px;
  height: 91px;
}
.bg {
  width: 100%;
  height: 100%;
  background: url(http://i60.tinypic.com/2j2fhjm.jpg) repeat-x left center;
  background-size: contain;
  -webkit-animation: displace 2s linear infinite;
  animation: displace 2s linear infinite;
}
@-webkit-keyframes displace {
  from {
    background-position: 0 center;
  }
  to {
    background-position: 160px center;
  }
}
@keyframes displace {
  from {
    background-position: 0 center;
  }
  to {
    background-position: 160px center;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <textarea class="bg"></textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

只要更改容器的尺寸,循环动画就会中断!

有没有办法让没有JS的响应?

val*_*als 26

问题是,要使其响应,您需要使用百分比设置动画背景位置.

但是,当您将background-size设置为cover或contains时,在某些情况下宽度会调整为100%.在这种情况下,使用百分比的背景位置是无用的(不会移动它).

我发现管理它的唯一方法是将图像移动到伪元素并移动它.但是,为了保持连续性,我们需要两个伪元素.

但这不适用于textarea.

你没有说textarea是一个要求,所以我发布这个.要显示它适用于调整大小,请将其悬停.

.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%);}
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="bg"></div>
</div>
<div class="container">
  <div class="bg"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

测试图像


Okk*_*kku 11

我通过使背景大两倍来使它成功.

我知道这不是一个完美的解决方案,但也许你可以用图像大小或其他东西来制作它,使它看起来像你想要的那样.

    .container {width: 160px;height: 91px;}
    .bg {
      width: 100%;
      height: 100%;
      background: url(http://i60.tinypic.com/2j2fhjm.jpg) repeat-x left center;
      background-size: 200%;
      -webkit-animation: displace 2s linear infinite;
      animation: displace 2s linear infinite;
    }
    @-webkit-keyframes displace {
      from { background-position: left center;
      } to { background-position: 200% center; }
    }
    @keyframes displace {
      from { background-position: left center;
      } to { background-position: 200% center; }
    }
Run Code Online (Sandbox Code Playgroud)
<div class="container"><textarea class="bg"></textarea></div>
Run Code Online (Sandbox Code Playgroud)