Animate CSS background-position with smooth results (sub-pixel animation)

感情迁移 提交于 2019-11-27 18:24:01

Checkout this example:

http://jsfiddle.net/5pVr4/4/

<div id="content">Foreground content
  <div class="bg"></div>
</div>

@-webkit-keyframes MOVE-BG {
   from {
     -webkit-transform: translateX(0);
   }
   to { 
     -webkit-transform: translateX(-187%);
   }
}

#content {
  height: 300px;
  text-align: center;
  font-size: 26px;
  color: #000;
  position:relative;
}

.bg{
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: -1;
  background: url(http://www.gstatic.com/webp/gallery/1.jpg) 0% 0% repeat;

  -webkit-animation-name: MOVE-BG;
  -webkit-animation-duration: 100s;
  -webkit-animation-timing-function: linear;
  -webkit-animation-iteration-count: infinite;
}

Animating background-position will cause some performance issues. Browsers will animate transform properties much cheaply, including translate.

Here is an example using translate for an infinite slide animation (without prefixes):

http://jsfiddle.net/brunomuller/5pVr4/504/

@-webkit-keyframes bg-slide {
    from { transform: translateX(0); }
    to { transform: translateX(-50%); }
}

.wrapper {
    position:relative;
    width:400px;
    height: 300px;
    overflow:hidden;
}

.content {
    position: relative;
    text-align: center;
    font-size: 26px;
    color: #000;
}

.bg {
    width: 200%;
    background: url(http://www.gstatic.com/webp/gallery/1.jpg) repeat-x;
    position:absolute;
    top: 0;
    bottom: 0;
    left: 0;
    animation: bg-slide 20s linear infinite;
}

You should adjust your HTML and CSS little bit

Working Demo

HTML

<div id="wrapper">
    <div id="page">
    Foreground content
</div>

<div id="content"> </div>
</div>

CSS

@-webkit-keyframes MOVE-BG {
    from { left: 0; }
    to { left: -2000px; }
}

#wrapper {
    position:relative;
    width:800px;
    height: 300px;
    overflow:hidden;
}

#page {
    text-align: center;
    font-size: 26px;
    color: #000;
}

#content {
    width: 2000px;
    height: 300px;
    background: url(http://www.gstatic.com/webp/gallery/1.jpg) 0% 0% repeat;
    position:absolute;
    top: 0;
    left: 0;
    z-index:-1;
    -webkit-animation-name: MOVE-BG;
    -webkit-animation-duration: 100s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!