31

Using CSS Custom Properties

In this Chapter

  • Learn what CSS custom properties are

  • Use various JavaScript methods to read and set CSS custom properties

When setting CSS properties with JavaScript, especially the really complex ones, you will often find yourself wrestling with strings:

var myCircle = document.querySelector("#myCircle");
setTranslate(50, 75, myCircle);
 
// Old approach
function setTranslate(xPos, yPos, el) {
  el.style.transform = "translate3d(" + xPos + ", " + yPos +
"px, 0)";
}
 
// Slightly better ES6-based old approach
function setTranslate(xPos, yPos, el) {
  el.style.transform = `translate3d(${xPos}px, ${yPos}px,
0)`;
}

Don’t get me wrong. I love a good string manipulation here and there, ...

Get Javascript Absolute Beginner's Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.