使用css实现太阳自转同时地球围着太阳公转的效果
<!DOCTYPE html>
<html>
<head>
<title>Solar System</title>
<style>
body {
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
.solar-system {
position: relative;
width: 400px;
height: 400px;
}
.sun {
width: 100px;
height: 100px;
background-color: yellow;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
animation: rotate 10s linear infinite; /* Sun rotation */
}
.earth {
width: 20px;
height: 20px;
background-color: blue;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
animation: orbit 20s linear infinite; /* Earth orbit */
}
@keyframes rotate {
from {
transform: translate(-50%, -50%) rotate(0deg);
}
to {
transform: translate(-50%, -50%) rotate(360deg);
}
}
@keyframes orbit {
from {
transform: translate(-50%, -50%) rotate(0deg) translateX(150px) rotate(0deg); /* Orbit radius */
}
to {
transform: translate(-50%, -50%) rotate(360deg) translateX(150px) rotate(-360deg); /* Counter-rotation for orbit */
}
}
</style>
</head>
<body>
<div class="solar-system">
<div class="sun"></div>
<div class="earth"></div>
</div>
</body>
</html>
Explanation and Improvements:
- HTML Structure: Sets up a basic structure with a
solar-system
div containing thesun
andearth
divs. - CSS Styling:
- Centers the solar system on the page.
- Styles the sun and earth as circles with appropriate colors.
- Uses
transform: translate(-50%, -50%);
to center the sun within its container.
- Animation:
@keyframes rotate
: Animates the sun's rotation usingtransform: rotate()
.@keyframes orbit
: Animates the earth's orbit. The key here is the combination oftranslateX()
to set the orbital distance and a counter-rotation usingrotate()
to keep the earth upright as it orbits. This creates the realistic orbiting effect.
- Adjustments:
- Orbit Radius: Change the
150px
in thetranslateX()
function within theorbit
animation to adjust the distance of the earth from the sun. - Animation Speed: Modify the duration values (e.g.,
10s
,20s
) in theanimation
properties to control the speed of rotation and orbit. - Adding More Planets: Duplicate the earth's code, change the class name (e.g.,
mars
), adjust thetranslateX()
value for the orbit radius, the animation duration, and thebackground-color
to add more planets. You can also adjust the size usingwidth
andheight
.
- Orbit Radius: Change the
This improved version provides a clearer explanation and more control over the animation parameters. It also addresses the crucial counter-rotation aspect for a realistic orbit. You can easily extend this example to create a more complex solar system simulation.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战