I recently wrote an article for 12 Days of Web on CSS content-visibility. Something I wanted to highlight in writing that article is that while the new HTML feature hidden=until-found uses content-visibility: hidden underneath, it works a little differently than how that property works on its own.
content-visibility: hidden vs. hidden=until-found
On its own, content-visibility: hidden will cause an element’s content to be completely hidden. This means it’s skipped for rendering, ignored by assistive technologies, and not findable using “find-in-page” browser features. The until-found value of the hidden attribute keeps the content findable which makes sense given its name, but otherwise it works the same.
Something I’d like to underscore is that it’s the hidden=until-found attribute-value pairing that makes content findable — not content-visibility: hidden. This means that in browsers that don’t support hidden=until-found yet, we can’t use content-visibility: hidden as a part of a polyfill. So, how would one polyfill this feature?
Hiding content while remaining findable
Now, while content-visibility: hidden does not keep content findable, content-visibility: auto does and reflecting on this got me thinking: could it be possible to polyfill hidden=until-found using content-visibility: auto?
Some differences between the auto and hidden values for the content-visibility property:
autokeeps content accessible whether or not the content is skipped for rendering.hiddenalways ignores the content in the accessibility tree.autoskips rendering while the content isn’t relevant. This means that if the content is in the viewport, it will be visible.- Both
autoandhiddenapply size, layout, paint, and style containment when the content is hidden.autodrops size containment when the content is visible. autokeeps content selectable.
So, we’ve got our grocery list of differences to address by using content-visibility: auto:
- We need the content ignored in the accessibility tree, but the element itself should still be accessible. This means we can’t set
aria-hidden=truedirectly on the element itself. - We need to visually hide both elements and text nodes.
- We need to ensure size containment is applied while the content is hidden.
- We need to make the content unselectable.
- We need to ensure elements cannot be clicked or focused.
We can address almost all but the first of these concerns with the following CSS:
[hidden="until-found"] {
display: revert;
content-visibility: auto;
contain: size;
user-select: none;
color: transparent;
> * {
opacity: 0;
pointer-events: none;
}
}
You’ll notice we’re setting display: revert. Wouldn’t that revert back to the user agent style for the hidden attribute which would be display: none? Nope — the hidden attribute is what’s called a presentational hint and the revert keyword reverts presentational hints (as well as non-user agent styles). While this is usually why you’d need to exercise caution when using the revert keyword, perhaps even opt-ing for revert-layer instead, this is the perfect use case: we want to revert back to the element’s user agent styles.
Now, we’re not done yet. And there are improvements to be made.
Setting color: transparent on the element itself is problematic as it affects currentColor which could be used by other properties of the element (e.g. like its border). Instead it would be great if we could set it on an inner element that wrapped the contents.
Finally, we want to make some of these styles easy to override. Others should not be an easy override. With the current styles, we need to be very specific about where and when they needed to be loaded to avoid cascading issues.
To make these improvements and to address the issue of accessibility, we’ll be going into the shadows…
Into the Shadow DOM
We can use a shadow root to address both our styling and accessibility concerns — not a phrase you might have expected someone to say about the Shadow DOM.
First, inside the shadow tree we’ll use a <slot> element to hide any slotted content from the accessibility tree and we’ll take that content out of the tab order, since <slot> elements are what’s called a focus navigation scope owner.
<slot aria-hidden=true tabindex=-1></slot>
Why tabindex=-1 and aria-hidden=true instead of the inert attribute? The inert attribute does do everything we need: it makes an element and all of its content hidden from the accessibility tree, makes the content unselectable, removes content from the tab order, and prevents content from being clicked or focused. It also does something undesirable for our purposes: it makes content hidden for “find-in-page” features. So, unfortunately, we’ll need to settle with a deconstructed version of it.
Now, another great advantage of using a <slot> element is that it’s an encapsulated element inside the tree that with its default styles of display: contents just visually displays all of the contents: text and elements. This is great because we still want the host element to be exposed to the accessibility tree and potentially a part of the tab order. We can also use it to fix some of our styling problems.
In a stylesheet for our shadow root, we move the color: transparent rule from the host element to the <slot> element. This means that color and currentColor can be used on the host element, but all slotted content will be transparent.
Here’s what the stylesheet looks like once we introduce the <slot> element and adapt it for the shadow DOM:
:host([hidden="until-found"]) {
display: revert;
content-visibility: auto;
contain: size;
user-select: none;
background-clip: initial !important;
slot {
color: transparent;
pointer-events: none;
}
::slotted(*) {
opacity: 0 !important;
}
}
A few notes:
- In order to use the attribute selector for the host element, we need to wrap with the
:host()functional pseudo-class. This selector allows us to select the shadow host which in our case will be the element withhidden=until-foundset on it. This element is not in the shadow tree, it’s the light DOM element that the shadow tree is attached to. That’s why we need a special selector to target it. - We’ve moved both the
colorandpointer-eventsproperties to the<slot>element. This reduces the restrictions we have on the host element. - We’re preventing the transparent text from being clipped by setting
background-clip: initial !importanton the host. This likely isn’t common, but since we’re usingcolor: transparenton a descendant usingbackground-clip: texton the parent with abackground-colorcould expose the content visually. - Since the slotted content is in the light DOM, we need to use the
::slotted()pseudo-element function with the universal selector to apply to all of the slotted elements. We’ve also made theopacity: 0rule important as shadow DOM styles can be too weak to ensure this applies otherwise, since they’re cascaded before the document styles.
Now that we have our styles finalized, we can start implementing the polyfilling logic to apply this to any element.
Revealing the content when found
Unfortunately, this is where we have to leave Safari by the wayside, as there’s no good way to observe its “find-in-page” feature. This means that we’re effectively only targeting Firefox.
While we’re preventing user selection with user-select: none, the “find-in-page” feature in Firefox selects the found text. This means that we can observe if our hidden content has been found with the selectionchange event on the document (or window).
document.addEventListener("selectionchange", event => {
const selection = document.getSelection();
const foundElement = selection.anchorNode?.parentElement.closest("[hidden=until-found]");
if (foundElement) {
const cancelled = !foundElement.dispatchEvent(
new Event("beforematch", { bubbles: true });
);
if (cancelled) return;
foundElement.removeAttribute("hidden");
const slot = foundElement.shadowRoot.querySelector("slot");
slot.removeAttribute("tabindex");
slot.removeAttribute("aria-hidden");
}
});
When the selection changes, we check if the selected content is within an element with hidden=until-found, the beforematch event isn’t cancelled, and if we’re clear, then we start its teardown:
- Removing the
hiddenattribute (like the actualhidden=until-foundfeature works), removes all of our styles. - Then we need to tear down the
tabindexandaria-hiddenattributes.
Afterward there is the shadow root leftover and while we can remove that if we replace the host with a shadow-less clone, we’ll lose the selection, which isn’t terribly hard to resolve, but it causes issues with the “find-in-page” feature which put me off from that approach.
Applying the polyfill
If we start a mutation observer early enough, we can both catch elements as they initially are parsed and later if there are any programmatic changes to the document. We can use this to polyfill the value for the global hidden attribute.
Here’s the configuration of our observer:
const hiddenUntilFoundObserver = new MutationObserver(callback);
hiddenUntilFoundObserver.observe(document, {
subtree: tree,
childList: true,
attributeFilter: ["hidden"],
});
Since we’re observing prior to the <body> element being parsed or constructed, we’ll just observe the document itself. We want to both observe every element mutation and hidden attribute mutations.
Before we get into the the observer callback, since we’re covering two types of mutations, we’ll need to abstract our shadow root setup code:
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:host([hidden="until-found"]) {
display: revert;
content-visibility: auto;
contain: size;
user-select: none;
background-clip: initial !important;
slot {
color: transparent;
pointer-events: none;
}
::slotted(*) {
opacity: 0 !important;
}
}
`);
function addShadow(element) {
if (element.shadowRoot) return;
element.attachShadow({ mode: "open" });
element.shadowRoot.innerHTML = "<slot aria-hidden=true tabindex=-1></slot>";
element.shadowRoot.adoptedStyleSheets = [sheet];
}
If the element already has a shadow root attached this bail early. This is a limitation of making this a generalized approach. It’s not an unsurmountable problem.
We’re also using the same constructed stylesheet between elements. This is fine since we’re not modifying the stylesheet.
Now for our callback…
const hiddenUntilFoundObserver = new MutationObserver(entries => {
for (const entry of entries) {
if (entry.type === "attributes" && entry.target.getAttribute("hidden") === "until-found") addShadow(entry.target);
else if (entry.type === "childList")
for (const node of entry.addedNodes)
if (node.getAttribute?.("hidden") === "until-found") addShadow(node);
}
});
For attributes mutation records, we only need to worry about one element which makes it straightforward to check the value of the hidden attribute. For childList mutation records, the addedNodes could be text nodes, so we need to optionally call the getAttribute() in our check.
Now, all of the polyfill’s code is written and we just need to feature check if we need the polyfill. In browsers that support the feature we can check if onbeforematch is in the document. We’ll also want to filter out Safari which we’ll just have to do a bit inelgantly just using a supports-check for user-select: none since there’s no way to feature-check “find-in-page.”
if ("onbeforematch" in document || !CSS.supports("(user-select: none)")) return;
Once that’s in place we’ve got our entire polyfill:
(function() {
if ("onbeforematch" in document || !CSS.supports("(user-select: none)")) return;
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:host([hidden="until-found"]) {
display: revert;
content-visibility: auto;
contain: size;
user-select: none;
background-clip: initial !important;
slot {
color: transparent;
pointer-events: none;
}
::slotted(*) {
opacity: 0 !important;
}
}
`);
const hiddenUntilFoundObserver = new MutationObserver(entries => {
for (const entry of entries) {
if (entry.type === "attributes" && entry.target.getAttribute("hidden") === "until-found") addShadow(entry.target);
else if (entry.type === "childList")
for (const node of entry.addedNodes)
if (node.getAttribute?.("hidden") === "until-found") addShadow(node);
}
});
hiddenUntilFoundObserver.observe(document, {
subtree: tree,
childList: true,
attributeFilter: ["hidden"],
});
document.addEventListener("selectionchange", event => {
const selection = document.getSelection();
const foundElement = selection.anchorNode?.parentElement.closest("[hidden=until-found]");
if (foundElement) {
const cancelled = !foundElement.dispatchEvent(
new Event("beforematch", { bubbles: true });
);
if (cancelled) return;
foundElement.removeAttribute("hidden");
const slot = foundElement.shadowRoot.querySelector("slot");
slot.removeAttribute("tabindex");
slot.removeAttribute("aria-hidden");
}
});
function addShadow(element) {
if (element.shadowRoot) return;
element.attachShadow({ mode: "open" });
element.shadowRoot.innerHTML = "<slot aria-hidden=true tabindex=-1></slot>";
element.shadowRoot.adoptedStyleSheets = [sheet];
}
})();
And here it is in action:
Summary of limitations
As mentioned, this does not work in Safari and you don’t need it in Chrome.
Due to issues with observing selection within shadow roots in Firefox, there’s no way we can make the polyfill work inside shadow roots.
And again, this also doesn’t work for elements that already have a shadow root.
Why even?
Given the limitations and especially the fact that this polyfill only applies to one browser, why bother polyfilling this? Well, to be completely honest I don’t find it worth polyfilling — especially since it would be quite easy to progressively enhance hidden=until-found usage. This was an interesting exercise in exploring findability in the browser. It’s something that authors don’t have direct control over. It takes a very thought out concoction of CSS and shadow DOM to even mimic something that is based on it. Perhaps this could be something that authors had greater control over in the future. Another part of browsers to unearth in making the platform extensible?
Contribute
If you want to use the final polyfill or contribute, you can do so on GitHub at knowler/hidden-until-found-polyfill.





