使用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.