This post was sparked by a question I answered on Quora: Which is better to use, CSS or JS?
Table of Contents
There are a few reasons why you should try to leverage the browser’s CSS engine instead of hand-rolling animations, focused states and so on.
CSS and HTML try their hardest to self-remedy. They’re super robust: one broken CSS rule doesn’t crash your whole web-app, a missing tag might break your layout but except in extreme cases it won’t stop your site from loading.
Since CSS is declarative there is a lot more scope for optimisation. The browser can sometimes use hardware acceleration to do CSS things.
It can also optimise things like not computing off-screen element’s styles or run their animations.
3. Easy and costly to get wrong
CSS is also quite cheap to interpret since it’s declarative, you can parallelise the creation of the in-memory representation of styles (since each selector in the CSS can be interpreted in parallel) and also defer calculation of the final styles until when the elements are painted.
5. Cost of maintenance and added dependencies
you’re adding a dependency with its own API, which means potentially more things to learn for anyone looking to maintain the code after you
CSS animations and detecting DOM state using pseudo-classes costs you nothing both in terms of loading and not incurring a dependency since CSS and HTML are backed by web standards. It’s very likely any new developers will be familiar with CSS animations, and if they’re not, they should be.
Feel free to get in touch with me on Twitter @hugo__df.
Leave some 👏🏻 if you enjoyed this, and here are some posts you might be interested in:
Get The Jest Handbook (100 pages)