首页 > 解决方案 > 在纯 CSS 中为元素添加图像背景大小动画效果

问题描述

为什么我无法在加载时添加更改 div 的背景图像大小的动画?我知道使用 JS 可以通过向 body 或元素添加一个类来实现这一点,但是我们如何在纯 CSS 中实现这一点?

html,body {
    height: 100%;
    width:100%;
    }

div {
    height: 100%;
    width:100%;
     background-image: url(https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg);
    background-size: 100%;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    animation-name: animate;
    transition: all 3s;
}

.animate {
  from {background-size: 100%}
  to {background-size: 110%}
}
<div></div>

标签: css

解决方案


html, body { height: 100%; width: 100%; }

div {
  height: 100%;
  width: 100%;
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg);
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  animation: animate 3s ease forwards;
  transition: all 3s;
}

@keyframes animate {
  from { background-size: 100%; }
  to {  background-size: 150%; }
}
<div></div>


推荐阅读