如何使用純CSS實現太陽和地球和月亮的運轉模型動畫

來源:互聯網
上載者:User
這篇文章給大家帶來的內容是關於如何使用純CSS實現太陽和地球和月亮的運轉模型動畫 ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

效果預覽

原始碼下載

https://github.com/comehope/front-end-daily-challenges

代碼解讀

定義dom,容器中包含 3 個元素:

<div class="container">    <div class="sun"></div>    <div class="earth">        <div class="moon"></div>    </div></div>

置中顯示:

body {    margin: 0;    height: 100vh;    display: flex;    align-items: center;    justify-content: center;    background-color: black;}

定義容器尺寸:

.container {    font-size: 10px;    width: 40em;    height: 40em;    position: relative;}

畫出太陽:

.sun {    position: absolute;    top: 15em;    left: 15em;    width: 10em;    height: 10em;    background-color: yellow;    border-radius: 50%;    box-shadow: 0 0 3em white;}

畫出地球和月球的軌跡:

.earth,.moon  {    position: absolute;    border-style: solid;    border-color: white transparent transparent transparent;    border-width: 0.1em 0.1em 0 0;    border-radius: 50%;}.earth {    top: 5em;    left: 5em;    width: 30em;    height: 30em;}.moon {    top:0;    right: 0;    width: 8em;    height: 8em;}

用虛擬元素畫出地球和月球:

.earth::before,.moon::before {    position: absolute;    border-radius: 50% ;   content: '';}.earth::before {    top: 2.8em;    right: 2.5em;    height: 3em;    width: 3em;    background-color: aqua;}.moon::before {    top: 0.8em;    right: 0.2em;     width: 1.2em;    height: 1.2em;    background-color: silver;}

設定運轉動畫效果:

/* rotation period 365.2422 days */.earth {    animation: orbit 36.5s linear infinite;   }/* rotation period 27.322 days */.moon {    animation: orbit 2.7s linear infinite;}@keyframes orbit {    to {        transform: rotate(360deg);    }}

最後,隱藏可能會出現在容器外的部分:

body {    overflow: hidden;}

大功告成!

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.