I'm trying to code a train leaving the 'station' but I'm not sure where to start. My idea requires the train to appear from the left and disappear into the right side of the screen. I inserted an image of a sketch I did for this concept. enter image description here
CodePudding user response:
You can find out about CSS translate (a transform) at https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate()
A useful feature of translate is that you can move an element by a % of its size.
So for your train you can start if off at translateX(-100%) which means it is just to the left of the viewport, out of site.
Then you want to move it to just off the right hand side of the viewport so you want to translate it 100vw;
Use a CSS animation to move it from left to right. This can be set up to run infinitely or just once or as many times as you want.
* {
padding: 0;
margin: 0;
}
body {
width: 100vw;
height: 100vh;
}
.train {
width: 50px;
height: 30px;
background-color: red;
display: inline-block;
transform: translateX(-100%);
animation-name: chug;
animation-duration: 5s;
animation-iteration-count: infinite;
}
@keyframes chug {
0% {
transform: translateX(-100%);
}
25% {
transform: translateX(50vw);
}
75% {
transform: translateX(50vw);
}
100% {
transform: translateX(100vw);
}
}
<div class="train"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
UPDATE: a pause has been put into the keyframes between 25% and 75% the train stays in the same place before moving off again.