求助:纯CSS实现的Slideshow无法正常运行,恳请协助排查问题
Hey there! Pure CSS slideshows can be sneaky—let’s walk through the most common issues that might be stopping yours from working properly:
Keyframe Animation Misconfiguration
The backbone of an auto-playing CSS slideshow is the@keyframesrule. Double-check that:- Your animation has clear start/end states (like
transform: translateX(0)for the first slide,transform: translateX(-100%)for the second, etc.). - You’ve applied the animation to the right element with all required properties:
animation-name,animation-duration,animation-iteration-count: infinite, andanimation-timing-function(e.g.,linearfor smooth transitions).
Example of a valid keyframe setup:
@keyframes slide { 0% { transform: translateX(0); opacity: 1; } 20% { transform: translateX(0); opacity: 1; } 25% { transform: translateX(-100%); opacity: 0.8; } 45% { transform: translateX(-100%); opacity: 1; } 50% { transform: translateX(-200%); opacity: 0.8; } 70% { transform: translateX(-200%); opacity: 1; } 75% { transform: translateX(-300%); opacity: 0.8; } 95% { transform: translateX(-300%); opacity: 1; } 100% { transform: translateX(0); opacity: 1; } }- Your animation has clear start/end states (like
Overflow and Container Setup Errors
Your slideshow container needsoverflow: hiddento hide slides that are outside the visible area. For horizontal slides:- The inner slides wrapper should have a width equal to the number of slides (e.g., 3 slides = 300% width).
- Slides should be set to
width: 100%of the container, so each takes up the full visible space.
If slides are stacking vertically instead of side-by-side, ensure you’re usingdisplay: flexon the wrapper orfloat: lefton slides (though flex is cleaner).
Broken Radio Button Toggle Logic (for manual control)
If you’re using hidden radio buttons to let users switch slides, make sure:- Each radio button has a unique
idthat matches theforattribute of its corresponding label. - Your CSS uses sibling selectors correctly to target the slides when a radio is
:checked. A common mistake is incorrect selector nesting that breaks the link between the radio and slide visibility.
Example of working selector:
#slide-1:checked ~ .slideshow-wrapper .slides { transform: translateX(0); } #slide-2:checked ~ .slideshow-wrapper .slides { transform: translateX(-100%); }- Each radio button has a unique
Timing and Delay Mismatches
For auto-play, ensure your animation duration aligns with how long each slide should stay visible. For 4 slides showing for 4 seconds each, your total animation duration should be 16 seconds (4s × 4 slides). If timings are off, slides might jump or not transition at all.
If you can share a snippet of your HTML and CSS here, I can pinpoint the exact issue for you!
内容的提问来源于stack exchange,提问作者Ricardo Moreira

