THIS IS THE WAY

Resize Observer CSS Class Toggler

Toggling CSS classes with Resize Observer to create responsive components, based on data attributes

Stefan Kandlbinder

--

There is already a very good article about “responsive” components and what Resize Observer can do for us.

But…

What about toggling CSS Classes based on data attributes?

The idea

resize-observer-css-class-toggler-idea

A data attribute “data-rob-{breakpoint}” represents the (mobile-first) breakpoint and the corresponding value “[CSS class] [CSS class] …” represents the CSS classes separated by spaces.

So, whenever the width of an HTML element reaches a breakpoint, the predefined CSS classes are added to the element.

This gives us the flexibility to create responsive components based on their width, defined once by CSS class modifiers and reusable over the whole site. The days of messing around with media queries are gone.

resize-observer-css-class-toggler-css
resize-observer-css-class-toggle-demo

You can also use this for state-based components that are not explicitly bound to their width e.g. a grid component.

resize-observer-css-class-toggler-state
resize-observer-css-class-toggler-state-demo

Endless Possibilities this is giving us!

Playgrounds

Codepen: https://codepen.io/StefanKandlbinder/pen/jOModNK?editors=0010
Stackblitz Angular Directive: https://stackblitz.com/edit/angular-resize-observer-css-class-toggler?file=src/app/ResizeObserverCSSClassToggler/resize-observer-css-class-toggler.directive.ts

Ready for feedback…

--

--