Computing with CSS Layout: How Grid, Flexbox, and anchor() Sort and Calculate Faster Than Raw calc()Article · digest for November 26
Physical installation on a typesetter's desk with rulers, grids, and paper CSS layout forms
Article5 sections≈ 12 min

Computing with CSS Layout: How Grid, Flexbox, and anchor() Sort and Calculate Faster Than Raw calc()

It's an odd paradox. We think of CSS as a language for spacing and colors, and reach straight for JavaScript whenever we need a maximum, a sort, or a median. Yet on every frame, the browser already runs fast layout algorithms. An auto column in Grid finds the widest cell, a Flexbox row sums its children's widths, and order sorts blocks by a number.

Even when JavaScript is disabled, blocked by CSP, or missing in an offline file, HTML and CSS still run. In his article Computing with CSS Layout, Agustín Capeletto showed how to feed data into the layout engine and read the answer back into a variable. On comparison-heavy tasks, it beats calc() formulas by an order of magnitude.

Computing with CSS Layout: calculations via the browser layout engine (Source: noscript.ing)

Reading Widths and Distances Back into a Number

Layout used to be a one-way street: the browser calculated a box's width and kept the result to itself. Three features closed the loop: container queries (container-type: inline-size), length division (100cqw / 1px), and @property.

A block inside inline-grid stretches across the full column. Put container-type: inline-size on it and it becomes a query container: descendants can read its width via 100cqw (100% of the container's width), while the container itself doesn't grow from its content. Divide 100cqw by 1px: in CSS Values Level 4, units cancel out, round() cleans up any remainder, and you get a plain number.

<div class="read">
  <i style="--value: 300">300</i>
  <b class="column-width">width = <output></output></b>
</div>

In this markup, <i> passes the number 300 and sets the shared column width, while the neighboring .column-width block stretches underneath it and displays the result in <output>. Now we wire them up with CSS:

/* Strict type freezes the number at declaration time */
@property --result {
  syntax: '<integer>';
  inherits: true;
  initial-value: 0;
}
.column-width {
  display: block;
  container-type: inline-size;
  > * { --result: round(100cqw / 1px); }
}
.read {
  display: inline-grid;
  grid-template-columns: auto;
  > i { width: calc(var(--value) * 1px); }
}
/* content cannot print a number directly, so a counter helps */
output::after {
  counter-reset: result var(--result);
  content: counter(result);
}

If you remove @property, the child inherits the round(100cqw / 1px) formula itself and recalculates it against another container. Registering <integer> locks in the computed 300.

The same trick measures distance using CSS Anchor Positioning. Give the target block anchor-name: --target, then stretch a measuring element from the parent's left edge to the anchor with right: anchor(--target left).

.position-track {
  position: relative;
  display: flex;
  > i { flex: none; }
  > .position-a { width: calc(var(--a) * 1px); }
  > .position-b { width: calc(var(--b) * 1px); }
  > .position-target { anchor-name: --target; }
  /* Measurer stretches from the left edge to the anchor */
  > .position-distance {
    position: absolute;
    left: 0;
    right: anchor(--target left);
    > .position-container {
      display: block;
      container-type: inline-size;
      > output { --result: round(100cqw / 1px); }
    }
  }
}

If two blocks sit before the anchor in a flex row, the measurer stretches to the exact sum of their widths. You get the coordinate without getBoundingClientRect().

Max in Grid, Sum in Flex, and Nested Calculations

Once geometry can flow back into a variable, layout properties act like math primitives. Three blocks sized 60px, 200px, and 150px in one Grid auto column push it out to the widest item, so the query container reads 200 without max(). A shrink-wrapped flex row gives the sum of its children's widths.

Primitives nest just like regular tags: two flex rows inside a Grid auto column compute 60 + 200 and 150 + 35 + 45, and the column returns their maximum of 260. That result can feed right back into a width, order, or grid-column. There is one tax: 100cqw reads the nearest query container, so the consumer must live inside the reader. Each calculation step needs three DOM levels: computation, query container, and consumers.

Indexing, Sorting with order, and Benchmarks vs. calc()

For a couple of numbers, calc() works fine on its own. Trouble starts when you compare every item against every other item: ranking 50 numbers in raw calc() takes 50 formulas of 49 comparisons each (2,450 comparisons). With min() and max(), that drops to 403, yet CSS size still grows with array length.

Layout skips pairwise comparisons. For picking by index --i, :nth-child() won't work (it expects a constant), but grid-column accepts a variable: each item sits in a column of its own width, and a query container at --i reads the answer.

For sorting and finding the median, items sit in the first row of an inline-grid with order: var(--value) and width calc(var(--value) * 1px). The browser lines them up in ascending order, and a query container in the middle column of the second row reads the median. Drag the slider below—sorting and median calculation run in pure CSS.

Live demo: sorting and finding the median with CSS Grid and order

When the slider drops below 75 or 55, the block jumps left without touching the DOM, and the badge under the third column prints the new median right away. There is one limit to order: it only accepts integers.

Ranking (the count of items before a given one after sorting) combines order and anchor(). Items sit in 100px columns (grid-auto-flow: column; grid-auto-columns: 100px), the target gets anchor-name: --ranked, and a measurer from the left edge divides width by 100px (round(100cqw / 100px)). On ties, whichever appears earlier in HTML comes first.

Chrome benchmarks on 300 changing numbers show how far layout pulls ahead of raw calc() on complex tasks.

Recalculation Time for 300 Numbers in Chrome: Pure calc() vs. Layout

Pure calc() suffers on both speed and stylesheet size: sorting 300 numbers generates 1.8 MB of CSS, and ranking generates 5.0 MB. Layout uses a tiny static stylesheet because adding an item gives work to the browser rather than bloating formulas. The table also shows an honest boundary: on prefix sums, raw calc() is slightly faster.

The dCSS Library and Charts Without JavaScript

To save you from wiring these patterns by hand, Capeletto released the MIT-licensed dCSS library (@noscripting/dcss on npm, also on jsDelivr CDN). It packs 63 functions modeled after D3.js (arrays, scales, number and date formats, math, motion), with class names mirroring D3's API (.dcss-bisect-left instead of d3.bisectLeft) and accuracy verified against D3's own test suite. You can import the whole bundle or single files like parts/dcss-mean.css.

The dcss-summarize class computes sum, mean, max, min, median, variance, and standard deviation in one shot:

<link rel="stylesheet" href="dcss.css">
<link rel="stylesheet" href="families/array.css">
<link rel="stylesheet" href="families/format.css">

<figure class="dcss-summarize dcss-format-fixed">
  <!-- Hide raw values from screen readers -->
  <ul aria-hidden="true">
    <li style="--value: 12"></li>
    <li style="--value: 40"></li>
    <li style="--value: 30"></li>
  </ul>
  <output style="--value: var(--dcss-sum); --precision: 0"></output>
  <output style="--value: var(--dcss-mean); --precision: 1"></output>
  <output style="--value: var(--dcss-max); --precision: 0"></output>
  <figcaption>Sum, mean, and max of 12, 40, and 30</figcaption>
</figure>

The page displays 82, 27.3, and 40 while keeping the HTML valid. The same foundation powers a dynamic adoption chart for six CSS features by month since 2016: a variable scrubs through months, shares come from @keyframes, curves are drawn in SVG and revealed via clip-path, and dcss-max rescales the Y axis with 10% headroom without JS.

There are three real-world constraints. First, values are encoded as pixel widths, so lists can easily overflow to the right—put overflow: clip on <figure>. Second, numbers render via ::after and counter(), so they don't exist in the DOM: screen readers ignore them, Ctrl+F won't find them, and users can't copy them (which is why <ul> gets aria-hidden="true" and <figcaption> repeats the meaning). Third, range limits: .dcss-summarize handles up to 1,024 integers from -1024 to 65535, while two-decimal dcss-decimals for min/max/extent work from -1310.72 to 82575.35. Overflow sets --dcss-err: 1, and an empty list sets --dcss-err: 2.

Browser Support and What Comes Next

By late 2026, almost the entire stack has landed in Baseline. Length division (100cqw / 1px) doesn't have a formal Baseline badge yet, but it already works across all three engines.

CSS FeatureBaselineChromeSafariFirefox
cqw unitsWidely105+16+110+
:has()Widely105+15.4+121+
@property202485+16.4+128+
round(), mod(), abs(), sign(), sin()2025138+15.4+118+
anchor-name and anchor()2026125+26+147+
Style queries for variables2026111+18+151+
sibling-index()2026138+26.2+154+
View timelines and timeline-scope2026116+26+159+
Length division (100cqw / 1px)None140+26+158+

The syntax will get even simpler soon. Typed attr() (Chrome 133+, Firefox 155+, not in Safari yet) lets you write data-value="60" instead of inline style="--value: 60". The if() function (Chrome 137+) picks values right on the element without parent style queries, and @function (Chrome 139+) packages named calculations. Pairing layout with timeline-scope and view timelines also lifts the three-level nesting rule, letting you pass a computed number anywhere on the page and into the next frame.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3