dom icon indicating copy to clipboard operation
dom copied to clipboard

Proposal: matchContainer API

Open ddamato opened this issue 4 months ago • 1 comments
trafficstars

What problem are you trying to solve?

While we have ResizeObserver which has been a great solution for a while now, I found one area where it's lacking; non-pixel units. If you wanted to observe when width of an element reaches 60ch, you'd have to determine what 60ch means in pixels, most likely by creating an element set as width: 60ch, measure it in pixels, and then use that number to compare within the observer's data. The reason why this is important is for component APIs, where we'd like the behavior of an internal structure to be configurable for outside consumers.

What solutions exist today?

If I wanted to allow a user to define a breakpoint for a component using Container Queries, it's cumbersome. Either due to the need of converting to pixels (which can also be inaccurate over the lifecycle) or the necessity to write the Container Query strictly in CSS in a local <style> tag. And when it's written in CSS, notifying JS that the container matches would be hacky at best, probably through animation triggers a la Style Observer.

How would you solve it?

I'd like to see an analog to the .matchMedia() method we'd see on window be available on Element as .matchContainer() to support Container Queries in a JS ecosystem.

We could have the following:

const $elem = document.querySelector('.my-target');
const cql = $elem.matchContainer('(max-width: 60ch)');

Where cql represents a ContainerQueryList (similar to the MediaQueryList). This would have the matches key meant to indicate if the element matches the query, the container key as the serialized container query and the ability to add a listener for when it changes:

cql.addEventListener('change', (ev) => {
  console.log(ev.matches);
})

Anything else?

No response

ddamato avatar Jun 21 '25 13:06 ddamato