前端每日实战:55# 视频演示如何用纯 CSS 创做一个太阳、地球、月亮的运转模型

图片描述

效果预览

按下右侧的“点击预览”按钮能够在当前页面预览,点击连接能够全屏预览。css

https://codepen.io/comehope/pen/RJjQYYhtml

可交互视频

此视频是能够交互的,你能够随时暂停视频,编辑视频中的代码。前端

请用 chrome, safari, edge 打开观看。git

https://scrimba.com/p/pEgDAM/cLQLyTRgithub

源代码下载

每日前端实战系列的所有源代码请从 github 下载:chrome

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

代码解读

定义dom,容器中包含 3 个元素:flex

<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;
}

定义容器尺寸:spa

.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;
}

大功告成!

相关文章
相关标签/搜索