Is it possible to use CSS transitions to animate something between a position set as left: 0px
to right: 0px
so it goes all the way across the scre
In more modern browsers (including IE 10+) you can now use calc():
.moveto {
top: 0px;
left: calc(100% - 50px);
}
If you know the width/height of the animated element you can animate the position (top, bottom, left, right) and then substract the corresponding margin.
.animate {
height: 100px;
width: 100px;
background-color: #c00;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
position: absolute;
left: 0; /*or bottom, top, right*/
}
And then animate depending on the position...
.animate.move {
left: 100%; /*or bottom, top, right*/
margin-left: -100px; /*or bottom, top, right */
}
This implementation would probably be smoother with transform: translate(x,y)
but I'll keep it like this so it's more understandable.
demo: http://jsfiddle.net/nKtC6/
This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.
topleft {
top: 0%;
left: 0%;
}
bottomright {
top: 100%;
left: 100%;
-webkit-transform: translate(-100%,-100%);
}
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {
position: fixed;
left: 0;
top: 0;
animation: 2s ease-in-out infinite alternate swingViewport;
/* just for styling purposes */
background: #c70039;
padding: 1rem;
color: #fff;
font-family: sans-serif;
}
@keyframes swingViewport {
from {
transform: translateX(0);
}
to {
transform: translateX(calc(100vw - 100%));
}
}
<div id="viewportPendulum">Viewport</div>
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {
position: relative;
display: inline-block;
animation: 2s ease-in-out infinite alternate swingParent;
/* just for styling purposes */
background: #c70039;
padding: 1rem;
color: #fff;
font-family: sans-serif;
}
@keyframes swingParent {
from {
transform: translateX(0);
left: 0;
}
to {
left: 100%;
transform: translateX(-100%);
}
}
.wrapper {
padding: 2rem 0;
margin: 2rem 15%;
background: #eee;
}
<div class="wrapper">
<div id="parentPendulum">Parent</div>
</div>
Note: This approach can easily be extended to work for vertical positioning. Visit example here.