Reactive Animations with CSS Variables

Despite its name, reactive animations have nothing to do with React, the framework/library/whatever it is. Rather, reactive animations can be described in terms of discrete changes caused by any number of events.

The overall idea is that JS captures multiple streams of events into a single stream, and emits those values over to CSS, where they are expressed as custom properties. By doing this, we can accomplish reactive styles.

The result is RxCSS, “a very small library for manipulating CSS Custom Properties (aka CSS Variables) with RxJS Observables”.

Not entirely familiar with CSS Variables? CSS Variables: var(–subtitle); is a good video/presentation to get you started.

Observing the scroll offset in an element could be coded as such:

// Observe scrolling in .content
const content = document
  .querySelector('.content');

const scroll$ = Rx.Observable
  .fromEvent(content, 'scroll')
  .map(({target}) =>
    2 * target.scrollTop / target.clientHeight);

// Couple the result of the `scroll$` observable to the `scroll` CSS Variable
RxCSS({
  scroll: scroll$,
});

In your CSS you can then use the scroll CSS Variable like one would normally do:

// Fade out background photo + scale it up when scrolling up one screen
.ui-bg-photo {
  opacity: calc(1 - var(--scroll));
  transform: scale(calc(1 + var(--scroll) / 3));
}

// Fade in the content when scrolling up
.ui-content {
  opacity: var(--scroll, 0);
}

The end result is this:

Reactive Animations with CSS Variables (Slides) →
Reactive Animations with CSS Variables (Video) →
RxCSS →

Elsewhere , , , ,

One Response to Reactive Animations with CSS Variables

  1. Pingback: An Animated Intro to RxJS | Bram.us

Leave a Reply

Your email address will not be published. Required fields are marked *