The initial solution was to put a container to limit the object's action:
@keyframes anima{
0%{ left: 0; }
50%{ left: 100%;}
100%{ left: 0; }
}
#container {
width:100%;
box-sizing:border-box;
position:relative;
padding-right:40px;
border:1px solid green;
}
#circle{
width: 40px;
height: 40px;
border-radius: 50%;
background-color: red;
position: relative;
top: 0;
left: 0;
animation: anima 8s infinite;
}
<body>
<div id="container">
<div id="circle"></div>
</div>
</body>
I took it and adjusted it in CSS. When you set a value of zero, you should not specify units.
The explanation is this: As you did the animation, what is being animated is the upper left corner of the object, so 100% means that the left margin will be at the edge of the screen (consequently the object will be out ).
By putting a padding on the right side, the same width as the object, we are compensating the size of this.
The green border is just for you to see the animation working properly. The margins left around the container are body
, I did not take it in the example CSS, but just add a rule in your CSS to remove them.
Finally,% w / o% makes our container 100% wide consider 100% including the padding that we insert into the measure (and to the green border ).
Evolving the idea
After a conversation in the comments, in which the author asked about the possibility of having a solution where the size of the padding does not have to be known beforehand, I came to a cleaner conclusion, which is not container dependent, and adjust to object size:
@keyframes anima{
0%{ left:0;transform:translateX(0); }
50%{ left:100%;transform:translateX(-100%); }
100%{ left:0;transform:translateX(0); }
}
#ball1, #ball2 {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: red;
position: relative;
left:0;
transform:translateX(0);
animation: anima 5s infinite ease-in-out;
}
#ball2 {
width:100px;
height:100px;
background-color:blue;
}
body, html {
margin:0;
padding:0;
}
<body>
<div id="ball1"></div>
<div id="ball2"></div>
</body>
The trick here was to tinker with the animation pivot, going from the top left to the top right, using box-sizing:border-box;
, so that when it reaches the right margin the object does not leave the screen.
I used to change the measures to simulate the full borderless screen, with the element really touching the edges.