Class-switched property assignment
Use JS to set a class. Directly update style declarations based on the class
Pattern 1
Pros
: Simple
Cons
: All style declarations are rewritten (not DRY), Need to maintain the class list of possible values. Duplicated declarations (slightly) slow CSSOM construction.
Class-switched Mixin call
Use JS to set a class. Call a mixin with the appropriate value based on the class.
Pattern 2
Pros
: DRY - Style declarations are written once. Logic is done in pre-processor land
Cons
: Need to maintain the class list of possible values. Duplicated declarations are (slightly) slower
Class-switched custom properties
Use JS to set a class. Set a custom property based on the class
Pattern 3
Pros
: DRY - Style declarations are written once. Pure CSS (no pre-processor features)
Cons
: Need to maintain the class list of possible values
JS switched custom properties
Use JS to set the custom property reference. Adam's favourite 🌟
Pattern 4
Pros
: DRY - Style declarations are written once. Clean & minimal CSS and JS code
Cons
: Need to know the name of the CSS variables used
JS defined custom property
Use JS to assign a value to the custom property
Pattern 5
Pros
: Keeps logic in JS, DRY - Style declarations are written once.
Cons
: Need to store key/value map in JS
Inline style manipulation
Use JS to set the style attribute directly
Pattern 6
Pros
: Everything lives in JS, Technically faster to render.
Cons
: Potential specificity conflicts, Need to store key/value map in JS, Need to update each property — not DRY
CSSOM manipulation
Similar to inline styling, but here we use JS to
update the CSSOM directly
.
Pattern 7
Pros
: Faster than inline, good unit type support
Cons
: Potential specificity conflicts, Need to store key/value map in JS, Need to update each property — not DRY. Limited browser support (Chrome & Edge)
Attribute switched custom properties
Similar to class-switching. Use JS to set an HTML attribute. Set a custom property based on that attribute
Pattern 8
Pros
: Attributes are easier to update than classList, DRY - Style declarations are written once.
Cons
: Need to maintain all possible values in CSS