DEV Community

tris timb
tris timb

Posted on

A simple way to specify In/Out css transitions

The CSS transition property

The transition property quickly brings animation to state changes on your page. It's simplicity is greatly appreciated when what you're animating is also simple. Consider the following:

.NavDrawer {
  transform: translateX(100%);
  transition: transform 300ms ease-in-out;
}

.NavDrawer.is-active {
  transform: translateX(0);
}
Enter fullscreen mode Exit fullscreen mode

With one property the mobile navigation drawer animates back and forth between its active position.

Cascading properties

What I want to focus on is the timing and easing parts of the property, and how we can specify different values based on direction.

.NavDrawer {
  transform: translateX(100%);
  transition: transform 300ms ease-in;
}

.NavDrawer.is-active {
  transform: translateX(0);
+ transition: transform 600ms ease-out;
}
Enter fullscreen mode Exit fullscreen mode

Taking advantage of CSS's cascading nature, we can specify a second transition property within the active selector. Here we can specify the 'in' transition, leaving the original one for the 'out' transition. This works because the .NavDrawer styling is overridden by the subsequent .is-active, then once the active state is removed it reverts back.

Takeaway

For many transitions animating out the same way they came in is desired, but I believe there are also instances of compromise for convenience. For example ease-in-out type easings are largely popular just for looking good in both directions. Now by specifying the direction usage of a simple transition is expanded, helping to easily make more desired transitions.

Top comments (0)