Static Animations with CSS Transition
This article is a part of my Web Animations article series.
The easiest thing to start with is CSS Transition. We will start by creating a visible element: <div class="box">Click me</div>
with
.box {
width: 100px;
height: 100px;
background-color: tomato;
}
Now we add the property transition
to our .box
:
transition: transform 500ms;
It means: The browser will render a transition effect when we change the property
transform
for500ms
.
That is the most basic form of animation inside the browser. We will now modify the box’ transform property when clicking on it:
const box = document.body.querySelector(".box")
box.addEventListener("click", () => {
box.style.transform = "translateX(100px)"
})
Here is what we get:
What is happening?
Right after page load the browser remembers the state of our box. He sees that there is no transform
specified, so he assumes the default value for this property. And this is “don’t translate the box” or “translate it by 0px”.
When we click on the box our JavaScript modifies the property transform
. Then the browser detects that our property transform
has changed. Because of our transition: transform 500ms
he knows that he should interpolate all values (from 1px, 2px, 3px … until 498px, 499px, 500px) within 500ms.
Now here is an important fact: He isn’t interpolating the transform
property itself. He is just interpolating the visual outcome.
We are not able to find out where our box exactly is during the animation. We just know that our box will be 100px to the right after 500ms.
Proof: I modified our example. The animation takes 5 seconds now. Every 50ms I will update the text-content of the box and write the current value of transform
inside it. See what is happening:
So remember, it is just the visual appearance that is animating when we use CSS Transition.