CSS Animation文本重叠问题:如何实现动画div不覆盖文本内容
Hey there! No worries at all about your English—totally get where you're coming from. Let's fix that overlapping issue with your animated div right away.
What's causing the overlap?
Your <span> uses position: absolute, while the <div> uses position: relative. In CSS, positioned elements that come later in the HTML flow will stack on top of earlier ones by default. That’s why your red animated div is covering the text. Plus, setting the div to 10000px in width/height is way larger than needed, which makes the overlap more noticeable.
Solutions to try
1. Give the text a higher stacking order (most straightforward)
Add a z-index value to your <span> to make it sit on top of the animated div. Since z-index only works on positioned elements (which your span already is), this will immediately fix the overlap:
<span>TEXT</span> <div></div>
div { width: 100vw; /* Use viewport width instead of 10000px for better responsiveness */ height: 100vh; /* Viewport height matches the screen size */ background: red; animation: divMove 5s linear infinite; position: relative; } @keyframes divMove { 0% { top: 0%; left: 0%; } 50% { top: 0%; left: 100%; } 100% { top: 0%; left: 0%; } } span { font-size: 50px; position: absolute; z-index: 10; /* Higher value = stacks above the div */ }
2. Send the animated div to the background
Alternatively, you can set a negative z-index on the div to push it behind the text. This works well if you don’t want to adjust the text’s positioning:
div { /* ... keep your existing styles ... */ z-index: -1; /* Puts the div below all default stacked elements */ }
Note: If the parent container of these elements has a background color or other positioned elements, this might cause the div to be hidden entirely. The first solution is more reliable for most cases.
3. Optimize the div's size (optional but recommended)
Using 10000px for width/height is unnecessary and can cause layout issues. Replace it with 100vw (100% of the viewport width) and 100vh (100% of the viewport height) to make the div fit the screen perfectly without extra overflow.
内容的提问来源于stack exchange,提问作者Andrew

