You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS中添加多张图片并结合@keyframes制作动画?

多张图片配合CSS @keyframes动画实现方案

方案1:多背景图轮播(无需修改现有HTML)

CSS的background-image属性本身支持同时加载多张图片,用逗号分隔即可,你可以直接基于现有body的背景配置扩展,实现背景图自动平滑切换效果:

@charset "utf-8";
/* CSS Document */
body {
  /* 多张背景图用逗号分隔,按顺序叠加 */
  background-image: url("Image/FreshFarmsBG.jpg"), url("Image/BG2.jpg"), url("Image/BG3.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  margin: 0;
  /* 调用动画:动画名 单次时长 无限循环 缓动效果 */
  animation: bgSlide 15s infinite ease-in-out;
} 

/* 定义横向滑动切换的背景动画 */
@keyframes bgSlide {
  0% {
    background-position: 0 0, 100vw 0, 200vw 0;
  }
  33% {
    background-position: -100vw 0, 0 0, 100vw 0;
  }
  66% {
    background-position: -200vw 0, -100vw 0, 0 0;
  }
  100% {
    background-position: 0 0, 100vw 0, 200vw 0;
  }
}

方案2:独立div实现多图片悬浮动画

如果需要实现多个独立的装饰图片浮动、弹跳等自定义效果,可以先修改HTML新增对应图片容器:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="style.css" rel="stylesheet" type="text/css"/>
<title>CSS Animation</title>
</head>
<body>
<main>
<!-- 新增动画图片容器 -->
<div class="anim-img item1"></div>
<div class="anim-img item2"></div>
<div class="anim-img item3"></div>

<nav>
<ul>
<li class="one"><a href="#">Menu 1</a></li>
<li class="two"><a href="#">Menu 2</a></li>
<li class="three"><a href="#">Menu 3</a></li>
</ul>
</nav>
</main>
</body>
</html>

对应的CSS代码:

@charset "utf-8";
/* CSS Document */
body {
  background-image: url("Image/FreshFarmsBG.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  margin: 0;
  position: relative;
  overflow-x: hidden;
} 

/* 通用动画图片样式 */
.anim-img {
  position: absolute;
  background-repeat: no-repeat;
  background-size: contain;
  /* 调用浮动动画 */
  animation: float 6s infinite ease-in-out;
}
/* 单独设置每个图片的资源、位置、尺寸、动画延迟,避免所有图片运动同步 */
.item1 {
  background-image: url("Image/fruit1.png");
  width: 120px;
  height: 120px;
  top: 15%;
  left: 10%;
  animation-delay: 0s;
}
.item2 {
  background-image: url("Image/fruit2.png");
  width: 100px;
  height: 100px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}
.item3 {
  background-image: url("Image/logo.png");
  width: 180px;
  height: 80px;
  top: 20%;
  right: 10%;
  animation-delay: 4s;
}

/* 定义上下浮动动画,可按需修改为旋转、缩放、透明度变化等效果 */
@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0px);
  }
}

/* 导航设置更高层级,避免被动画图片遮挡 */
nav {
  position: relative;
  z-index: 10;
}

内容的提问来源于stack exchange,提问作者Gus05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:45:04