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

如何将全屏CSS背景动画仅限定在指定div区块内显示?

Fix: Restrict Background Animation to .c Div Only

Hey Mario, I see exactly what's going on here—your background animation is using position: fixed, which anchors it to the viewport (the whole screen) instead of its parent .c div. Let's adjust this step by step to lock the animation inside .c:

Key Issues to Fix

  • The .bg elements use position: fixed, which ignores parent container boundaries
  • The .c div doesn't have a positioning context to contain absolute-positioned children

Modified Code Solution

<style>
body { margin:0; }
/* Make .c a positioning container for its children */
.c {
  margin:0 auto;
  position: relative; /* Critical: creates a positioning context */
  min-height: 100vh; /* Optional: if you want .c to take full viewport height */
  overflow: hidden; /* Prevents animation from spilling outside .c */
}
.bg {
  animation:slide 3s ease-in-out infinite alternate;
  background-image: linear-gradient(-60deg, #6c3 50%, #09f 50%);
  bottom:0;
  left:-50%;
  opacity:.5;
  position:absolute; /* Changed from fixed to absolute */
  right:-50%;
  top:0;
  z-index:-1; /* Keeps background behind content */
}
.bg2 {
  animation-direction:alternate-reverse;
  animation-duration:4s;
}
.bg3 {
  animation-duration:5s;
}
@keyframes slide {
  0% { transform:translateX(-25%); }
  100% { transform:translateX(25%); }
}
.content {
  position: relative; /* Ensures content stays above background */
  z-index: 1;
  padding: 2rem; /* Optional: adds space around content */
}
.footer {
  padding: 2rem;
  background: white; /* Optional: clearly separates from animated area */
}
</style>

<div class="c">
  <div class="bg"></div>
  <div class="bg bg2"></div>
  <div class="bg bg3"></div>
  <div class="content">
    <h1>Only here animation</h1>
  </div>
</div>
<!-- /end animation -->
<div class="footer">Here without animation</div>

What Changed & Why

  1. Added position: relative to .c: This tells absolute-positioned child elements (like .bg) to use .c as their positioning reference instead of the viewport.
  2. Changed .bg from position: fixed to absolute: Now the background elements are bound to the .c div's boundaries.
  3. Added overflow: hidden to .c: Stops the sliding background from peeking outside the .c container.
  4. Added position: relative and z-index:1 to .content: Makes sure your text stays visible above the animated background layers.
  5. Optional min-height:100vh on .c: If you want the animated area to fill the whole screen height (adjust this to fit your layout needs).

Now your animation will be confined strictly to the .c div, and the footer below will remain animation-free!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:40:44