Documents v0.9.0 · previews run the real runtime · experimental features are marked exp

Element size

A card reads its own measured width, and its text follows.

element():on()experimental
Live previewreal runtime

Drag the slider, or focus it and use the arrow keys. Narrow the window to see the measured width differ from the slider value.

How it works

  • element()line 10The element’s own border-box width or height in px, from one shared ResizeObserver.
  • :on()line 5An event rule: when the event happens on the matched element (or inside it, for bubbling events), the rule’s state mutations run. The cascade picks one winning mutation per state, per trigger and per element.

element(width) gives an element its own measured width as a CSS length. The text inside the card is sized from that measurement, not from the slider value, so it also follows when the card is limited by the available space.

Native CSS alternative

Container queries and container units (cqw) size content from a container and are usually the better tool. element() measures the element itself, which container units cannot.

Limitations

  • There is no value before the first measurement, so var(--w, 300px) gives a fallback for that first frame.
  • Do not size the element from its own measurement (width: calc(element(width) + 10px)): the runtime detects that loop and freezes the value.

Implementation

2 files · 13 lines
style.cssreactive
/* ---- Reactive CSS -------------------------------------------------------------------------- */.size { --width: state(300); }/* The slider sets the section's state at each input. */.size .width:on(input) { --width: set(event(value-as-number)); }.size .set { content: var(--width); }.size .card {  width: min(var(--width) * 1px, 100%);  --w: element(width);                          /* the card's own border-box width */}.size .big { font-size: calc(var(--w, 300px) / 6); }   /* follows the measured width */.size .measured::after { counter-reset: w round(var(--w, 0px) / 1px); content: counter(w); }
state()Function · hover any red tokenMakes each matching element the owner of an independent state with an initial value.Reference →

Source: site/src/catalog/api/element-size/. style.css from its Reactive CSS divider; the layout above it and the shared api.css run but are not shown.

Related

State history

A score that remembers its last value and which way it moved.

previous()direction():changed()

Random colors

Each click rolls a new hue and picks a new name.

random()set()

Context menu

Right-click anywhere on the desk to open a custom menu where you clicked.

experimental:on()prevent()event()focus: