简体   繁体   English

如何在 CSS 中为背景图像设置动画?

[英]How to animate background-image in CSS?

I have this animation:我有这个动画:

@keyframes floating {
  from { transform: translate(0,  0px); }
  65%  { transform: translate(0, 15px); }
  to   { transform: translate(0, -0px); }    
}

and I want to insert this animation on background-image.我想在背景图像上插入这个动画。 How to do this?这该怎么做? Thank you.谢谢你。

See if this approach would work for you:看看这种方法是否适合你:
https://codepen.io/panchroma/pen/RYbGwB https://codepen.io/panchroma/pen/RYbGwB

The idea is that you:这个想法是你:

(1) style the element you are working with position:relative; overflow:hidden; (1) 为你正在使用的元素设置样式position:relative; overflow:hidden; position:relative; overflow:hidden; then然后
(2) apply the animation to an absolutely positioned pseudo element .element:before{...} (2) 将动画应用到绝对定位的伪元素.element:before{...}

HTML HTML

<div class="element"></div>  

CSS CSS

.element{
  position: relative;
  overflow:hidden;
  width: 600px;
  height: 400px;
}

.element:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 600px;
  height: 400px;
  animation: floating 5s infinite;
  z-index: -1;
 background-image:url(https://github.com/bradleyflood/tool-sample-testing-images/raw/master/jpg-beach-1020x670-160kb.jpg)
}


@keyframes floating {
  from { transform: translate(0,  0px); }
  65%  { transform: translate(0, 15px); }
  to   { transform: translate(0, -0px); }    
}

I would like to take credit for this idea, it's from Craig Buckler though ;)我想归功于这个想法,虽然它来自Craig Buckler ;)

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM