利用CSS3实现太阳、地球和月球旋转特效

36 min read

以下是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%;
  • 地球和月球都是绝对定位,使用topleft属性相对于太阳的中心位置定位,margin-topmargin-left属性设置偏移量;
  • 使用CSS3动画属性animation实现旋转动画,其中animation-name属性指定动画的名称,animation-duration属性指定动画的时间长度,animation-iteration-count属性指定动画的循环次数,animation-timing-function属性指定动画的时间函数;
  • 最后使用keyframes关键字创建动画的帧,通过设置transform属性的rotate函数实现旋转。其中deg表示角度单位,360度表示一周。

效果如下:

太阳地球月球旋转