Computing with CSS Layout and the dCSS library 🧮⚡️
← Go back

Computing with CSS Layout and the dCSS library 🧮⚡️

How to turn the browser layout engine into a calculator using Container Queries and @property, and how the 63-function dCSS library works under the hood.

Computing with CSS Layout and the dCSS library 🧮⚡️

In his article “Computing with CSS Layout,” Agustín Capeletto demonstrated how to turn the browser’s layout engine into a calculator. The idea is simple: the browser already computes element dimensions and positions on every frame, so why not feed those results back into your styles?

  • flex sums up the widths of items;
  • grid with an auto column computes max();
  • order sorts elements without pairwise comparisons;
  • anchor() measures the distance between nodes.

To convert a computed length back into a unitless number, it combines Container Queries and @property: an element is given container-type: inline-size, and its width is read via --result: round(100cqw / 1px) into a typed <integer> custom property.

The dCSS library built on top of it 📦

Building on these primitives, the authors created dCSS—a CSS library featuring 63 data-processing functions (named and tested after d3.js), organized into 5 modules:

  • Arrays and statistics: sums, mean, median, variance, sorting, and key lookup (lookup, bisect).
  • Scales: linear, logarithmic, power, and ordinal scales.
  • Formatting: percentages, SI prefixes, and localized numbers and currencies.
  • Math and physics: numerical root-finding (Newton’s method) and motion simulation.

How it works

You import the CSS file you need (even individual functions cherry-picked one by one), pass numbers via --value into a list inside <figure class="dcss-mean">, and immediately read the result from --dcss-mean or render it inside an <output> element. One amusing caveat: because the math is tied to layout pixels, calculations only work accurately at integer display scaling factors (100%, 200%, Retina) and produce rounding errors at fractional zoom levels like 125% or 150%.

👉 Article and demos: noscript.ing/compute (opens in new tab)

👉 dCSS repository: github.com/noscripting/dCSS (opens in new tab)

What do you think of this approach? An impressive showcase of modern CSS specifications, or pure overengineering for the fun of it? 👇

Copied