以下是HTML和CSS代码,可以模拟太阳、地球、月球旋转的特效:
<div class="sun"> <div class="earth"> <div class="moon"></div> </div> </div>
.sun { width: 200px; height: 200px; border-radius: 50%; background-color: #ffd800; position: relative; animation-name: rotate-sun; animation-duration: 10s; animation-iteration-count: infinite; animation-timing-function: linear; } .earth { width: 80px; height: 80px; border-radius: 50%; background-color: #1e90ff; position: absolute; top: 50%; left: 50%; margin-top: -40px; margin-left: -40px; animation-name: rotate-earth; animation-duration: 5s; animation-iteration-count: infinite; animation-timing-function: linear; } .moon { width: 30px; height: 30px; border-radius: 50%; background-color: #f0f0f0; position: absolute; top: 50%; left: calc(50% + 80px); margin-top: -15px; animation-name: rotate-moon; animation-duration: 2s; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes rotate-sun { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } @keyframes rotate-earth { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } @keyframes rotate-moon { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
解析:
- 太阳是一个圆形元素,使用
border-radius
属性设置圆角半径为50%; - 地球和月球也是圆形元素,使用
border-radius
属性设置圆角半径为50%; - 地球和月球都是绝对定位,使用
top
和left
属性相对于太阳的中心位置定位,margin-top
和margin-left
属性设置偏移量; - 使用CSS3动画属性
animation
实现旋转动画,其中animation-name
属性指定动画的名称,animation-duration
属性指定动画的时间长度,animation-iteration-count
属性指定动画的循环次数,animation-timing-function
属性指定动画的时间函数; - 最后使用
keyframes
关键字创建动画的帧,通过设置transform
属性的rotate
函数实现旋转。其中deg
表示角度单位,360度表示一周。
效果如下: