HTML-CSS动画问题:inner-inner-circle旋转时超出inner-circle范围
解决你的两个HTML-CSS精灵问题
一、搞定整体居中与响应式适配
- 页面居中:给
html和body设置height:100vh,通过Flex布局让整个精灵容器在页面垂直水平居中,同时添加overflow:hidden避免不必要的滚动条。 - 响应式尺寸:
outer-circle改用width:90vw(占视口宽度90%),配合max-width:600px限制最大尺寸,用aspect-ratio:1/1维持正方形比例,替代固定宽高。- 内部所有圆形元素(
inner-circle、halph-moon、cover)都使用百分比宽度+aspect-ratio:1/1,确保在不同屏幕下都保持圆形,不会变形。
- 绝对定位修正:给
outer-circle添加position:relative,让内部的halph-moon和cover以它为定位基准,改用right百分比替代固定left值,确保它们随容器一起缩放,不会偏移到页面其他区域。
二、修正inner-inner-circle旋转偏移问题
- 初始位置校准:将
inner-inner-circle改为绝对定位,通过top:50%; left:50%; transform:translate(-50%, -50%)让它始终居中在inner-circle内部,替代原来的固定top和left值。 - 动画逻辑调整:
- 原动画中的
translateY(100%)会将元素移出inner-circle,现在调整为:先保持居中的translate(-50%, -50%),再添加translateY(-50%)将元素移到inner-circle顶部边缘,最后执行rotate(360deg),实现内部旋转效果。 - 默认旋转中心点为元素自身中心,若需调整旋转位置,修改
transform-origin属性即可。
- 原动画中的
修改后的完整代码
<!DOCTYPE html> <html> <head> <title>CSS Sprite Animation</title> <style> *{ margin: 0; padding: 0; box-sizing: border-box; } /* 页面整体居中 */ html, body { height: 100vh; display: flex; justify-content: center; align-items: center; overflow: hidden; } .outer-circle{ position: relative; /* 作为内部绝对定位元素的基准 */ width: 90vw; max-width: 600px; aspect-ratio: 1/1; background-color: green; border-radius: 50%; z-index: 0; } .inner-circle{ position: relative; top: 5%; width: 50%; aspect-ratio: 1/1; background-color: yellow; border-radius: 50%; margin: 0 auto; } .inner-inner-circle{ position: absolute; z-index: 4; width: 50%; aspect-ratio: 1/1; background-color: black; border-radius: 50%; /* 居中定位 */ top: 50%; left: 50%; transform: translate(-50%, -50%); animation: changebg 5s linear 2s infinite alternate; } .halph-moon{ position: absolute; z-index: 1; width: 83.33%; aspect-ratio: 1/1; border-radius: 50%; background-color: black; top: 8.33%; right: -41.67%; } .cover{ position: absolute; z-index: 2; width: 70%; aspect-ratio: 1/1; border-radius: 50%; background-color: green; top: 2.5%; right: -15%; } @keyframes changebg{ 0%{ background-color: black; transform: translate(-50%, -50%) translateY(-50%) rotate(0deg); } 100%{ background-color: red; transform: translate(-50%, -50%) translateY(-50%) rotate(360deg); } } </style> </head> <body> <div class="outer-circle"> <div class="cover"></div> <div class="halph-moon"></div> <div class="inner-circle"> <div class="inner-inner-circle"></div> </div> </div> </body> </html>
内容的提问来源于stack exchange,提问作者KmerPadreDiPdor
相关产品推荐
相关产品推荐

