Native mechanisms for toggling content

Reaching for display: none or opacity: 0 plus a bit of JavaScript is the habitual route, but native toggling APIs have matured. Choosing between disclosures, the Dialog API and the Popover API depends on whether the overlay should be modal or non-modal, and whether JavaScript is acceptable.

Disclosures: <details> and <summary>

Use case: accessibly summarizing content, with the details toggleable individually or grouped as an accordion.

Disclosures were the first way to toggle content without JavaScript or checkbox hacks, but early browser support lacked keyboard accessibility — so many developers stopped using them after they arrived in Chrome 12 in 2011. The current state:

  • Works without JavaScript, without compromises.
  • Fully stylable without appearance: none or similar.
  • The marker can be hidden without non-standard pseudo-selectors.
  • Multiple disclosures can be connected into an accordion.
  • Fully animatable as of 2024.

The markup looks like this:

<details>
  <summary>Content summary (always visible)</summary>
  Content (visibility is toggled when summary is clicked on)
</details>

Internally, the content is wrapped in a pseudo-element — selectable as ::details-content as of 2024 — and a ::marker pseudo-element indicates open or closed state:

<details>
  <summary><::marker></::marker>Content summary (always visible)</summary>
  <::details-content>
      Content (visibility is toggled when summary is clicked on)
  </::details-content>
</details>

Adding the open attribute to <details> makes it open by default; this is also what happens behind the scenes when a disclosure is opened.

<details open> ... </details>

Styling and interactivity

The marker disappears when display on <summary> is set to anything but list-item:

summary {
  display: block; /* Or anything else that isn't list-item */
}

The marker itself can be replaced — the example below uses Font Awesome — but ::marker accepts only a limited set of properties, so the most flexible approach is wrapping the summary's content in an element and targeting that:

<details>
  <summary><span>Content summary</span></summary>
  Content
</details>
details {
  
  /* The marker */
  summary::marker {
    content: "\f150";
    font-family: "Font Awesome 6 Free";
  }

  /* The marker when <details> is open */
  &[open] summary::marker {
    content: "\f151";
  }
  
  /* Because ::marker doesn’t support many properties */
  summary span {
    margin-left: 1ch;
    display: inline-block;
  }
  
}

Multiple disclosures sharing a name attribute with matching values (much like <input type="radio">) form an accordion; they don't even need to be siblings:

<details name="starWars" open>
  <summary>Prequels</summary>
  <ul>
    <li>Episode I: The Phantom Menace</li>
    <li>Episode II: Attack of the Clones</li>
    <li>Episode III: Revenge of the Sith</li>
  </ul>
</details>

<details name="starWars">
  <summary>Originals</summary>
  <ul>
    <li>Episode IV: A New Hope</li>
    <li>Episode V: The Empire Strikes Back</li>
    <li>Episode VI: Return of the Jedi</li>
  </ul>
</details>

<details name="starWars">
  <summary>Sequels</summary>
  <ul>
    <li>Episode VII: The Force Awakens</li>
    <li>Episode VIII: The Last Jedi</li>
    <li>Episode IX: The Rise of Skywalker</li>
  </ul>
</details>

With a wrapper, the same pattern becomes horizontal tabs:

<div> <!-- Flex wrapper -->
  <details name="starWars" open> ... </details>
  <details name="starWars"> ... </details>
  <details name="starWars"> ... </details>
</div>
div {
  gap: 1ch;
  display: flex;
  position: relative;

  details {
    min-height: 106px; /* Prevents content shift */
      
    &[open] summary,
    &[open]::details-content {
      background: #eee;
    }

    &[open]::details-content {
      left: 0;
      position: absolute;
    } 
  }
}

The same HTML can produce vertical tabs using 2024's Anchor Positioning API:

div {
  
  display: inline-grid;
  anchor-name: --wrapper;

  details[open] {
      
    summary,
    &::details-content {
      background: #eee;
    }

    &::details-content {
      position: absolute;
      position-anchor: --wrapper;
      top: anchor(top);
      left: anchor(right);
    } 
  }
}

JavaScript hooks into the toggle state:

// Optional: select and loop multiple disclosures
document.querySelectorAll("details").forEach(details => {
  details.addEventListener("toggle", () => {
    // The disclosure was toggled
    if (details.open) {
      // The disclosure was opened
    } else {
      // The disclosure was closed
    }
  });    
});

Accessibility constraints

<summary> behaves like a <label>: its content is announced by screen readers when focused. Without a <summary>, or if it isn't a direct child of <details>, the user agent generates a label that usually reads "Details" both visually and in assistive tech. Older browsers may require it to be the first child, so keep it there.

<summary> carries the role of button, so anything invalid inside a <button> is invalid inside a <summary>. That includes headings: a summary can be styled as a heading, but a heading cannot be nested inside it.

The <dialog> element

Use case: modals.

Since the Popover API covers non-modal overlays without JavaScript, dialogs are best thought of as modals — even though show() permits non-modal dialogs. A modal is an overlay that makes the main document inert; non-modal overlays leave it interactive. Modal dialogs bring these features out of the box:

  • a stylable backdrop,
  • autofocus on the first focusable element inside the dialog (falling back to the dialog itself — give it an aria-label in that case),
  • a focus trap, a consequence of the main document's inertia,
  • esc closes the dialog,
  • the dialog and its backdrop are animatable.

Markup and activation

Start with the element:

<dialog> ... </dialog>

It is hidden by default and, as with <details>, can be open on page load. Since it isn't opened with showModal(), it is not modal in that state:

<dialog open> ... </dialog>

More commonly, a button reveals it:

<button>Open dialogA</button>

The data attribute passes an identifier telling JavaScript which dialog to open, so one snippet can serve every dialog on the page:

// Select and loop all elements with that data attribute
document.querySelectorAll("[data-dialog]").forEach(button => {
  // Listen for interaction (click)
  button.addEventListener("click", () => {
    // Select the corresponding dialog
    const dialog = document.querySelector(`#${ button.dataset.dialog }`);
    // Open dialog
    dialog.showModal();      
    // Close dialog
    dialog.querySelector(".closeDialog").addEventListener("click", () => dialog.close());
  });
});

The dialog needs a matching id:

<dialog id="dialogA"> <!-- id and data-dialog = dialogA --> ... </dialog>

And a close button:

<dialog id="dialogA">
  <button class="closeDialog">Close dialogA</button>
</dialog>

Note: <form method="dialog"> (containing a <button>) or <button formmethod="dialog"> (wrapped in a <form>) also closes the dialog.

Scroll locking, backdrop and resets

One line of CSS prevents scrolling while the modal is open:

body:has(dialog:modal) { overflow: hidden; }

The backdrop that dims the content underneath the top layer (modals only) can be restyled:

::backdrop {
  background: hsl(0 0 0 / 90%);
  backdrop-filter: blur(3px); /* A fun property just for backdrops! */
}

The <dialog> itself ships with a border, a background and some padding that you may want to reset; popovers behave the same way.

Non-modal dialogs

For a non-modal dialog, use show() instead of showModal(), and target dialog[open] (which covers both) instead of dialog:modal. Since the Popover API needs no JavaScript for non-modal overlays, it is the better fit there.

The Popover API

Use case: non-modal overlays — tooltips (or toggletips — the distinction matters), onboarding walkthroughs, notifications, togglable navigations and anything else where the main document must stay accessible. Functionally popovers resemble dialogs, but they are not modal and require no JavaScript.

Markup

The popover needs an id and a popover attribute: manual (clicking outside won't close it), auto (clicking outside does close it), or no value (same as auto). A <dialog> can serve as the popover for semantics:

<dialog id="tooltipA" popover> ... </dialog>

A <button> or <input type="button"> with popovertarget matching the popover's id toggles its visibility (optional when clicking outside closes it anyway, i.e. not with manual):

<dialog id="tooltipA" popover>
  <button popovertarget="tooltipA">Hide tooltipA</button>
</dialog>

popovertarget toggles by default; the popovertargetaction attribute accepts show, hide or toggle to override that.

Positioning

Popovers are centered in the top layer like dialogs by default — usually not what you want for something non-modal:

<main>
  <button popovertarget="tooltipA">Show tooltipA</button>
</main>

<dialog id="tooltipA" popover>
  <button popovertarget="tooltipA">Hide tooltipA</button>
</dialog>

Fixed positioning pushes one into a corner, but tooltip-style popovers should sit relative to their trigger. CSS Anchor Positioning handles that:

main [popovertarget] {
  anchor-name: --trigger;
}

[popover] {
  margin: 0;
  position-anchor: --trigger;
  top: calc(anchor(bottom) + 10px);
  justify-self: anchor-center;
}

/* This also works but isn’t needed
unless you’re using the display property
[popover]:popover-open {
    ...
}
*/

Naming every anchor is overkill for a site with many tooltips. An id on the button can be matched to an anchor attribute on the popover — poorly supported as of November 2024, but workable for a demo:

<main>
  <!-- The id should match the anchor attribute -->
  <button id="anchorA" popovertarget="tooltipA">Show tooltipA</button>
  <button id="anchorB" popovertarget="tooltipB">Show tooltipB</button>
</main>

<dialog anchor="anchorA" id="tooltipA" popover>
  <button popovertarget="tooltipA">Hide tooltipA</button>
</dialog>

<dialog anchor="anchorB" id="tooltipB" popover>
  <button popovertarget="tooltipB">Hide tooltipB</button>
</dialog>
main [popovertarget] { anchor-name: --anchorA; } /* No longer needed */

[popover] {
  margin: 0;
  position-anchor: --anchorA; /* No longer needed */
  top: calc(anchor(bottom) + 10px);
  justify-self: anchor-center;
}

Tooltips are also expected to appear on hover, which calls for JavaScript. Tip pseudo-elements with ::before/::after/content: are simpler, but content: accepts only text whereas popovers accept HTML — which technically makes those toggletips.

JavaScript behavior and events

Anchor attributes avoid a CSS block per anchor element. Popovers are HTML-focused, so anchor positioning is used the same way. JavaScript calls showPopover() on mouseover and hidePopover() on mouseout — except when a popover contains a link, which must stay clickable (in that case the button that hides the popover is also kept):

<main>
  <button id="anchorLink" popovertarget="tooltipLink">Open tooltipLink</button>
  <button id="anchorNoLink" popovertarget="tooltipNoLink">Open tooltipNoLink</button>
</main>

<dialog anchor="anchorLink" id="tooltipLink" popover>Has <a href="#">a link</a>, so we can’t hide it on mouseout
  <button popovertarget="tooltipLink">Hide tooltipLink manually</button>
</dialog>

<dialog anchor="anchorNoLink" id="tooltipNoLink" popover>Doesn’t have a link, so it’s fine to hide it on mouseout automatically
  <button popovertarget="tooltipNoLink">Hide tooltipNoLink</button>
</dialog>
[popover] {
  
  margin: 0;
  top: calc(anchor(bottom) + 10px);
  justify-self: anchor-center;

  /* No link? No button needed */
  &:not(:has(a)) [popovertarget] {
    display: none;
  }
}
/* Select and loop all popover triggers */
document.querySelectorAll("main [popovertarget]").forEach((popovertarget) => {
  
  /* Select the corresponding popover */
  const popover = document.querySelector(`#${popovertarget.getAttribute("popovertarget")}`);
  
  /* Show popover on trigger mouseover */
  popovertarget.addEventListener("mouseover", () => {
    popover.showPopover();
  });

  /* Hide popover on trigger mouseout, but not if it has a link */
  if (popover.matches(":not(:has(a))")) {
    popovertarget.addEventListener("mouseout", () => {
      popover.hidePopover();
    });
  }
});

Timed backdrops and sequenced popovers

A backdrop on a popover seemed like an oversight at first, since it shouldn't obscure a focusable main document. But briefly dimming attention is fine as long as work can resume without being forced to close anything — which suits a set of onboarding tips:

<!-- Re-showing ‘A’ rolls the onboarding back to that step -->
<button popovertarget="onboardingTipA" popovertargetaction="show">Restart onboarding</button>
<!-- Hiding ‘A’ also hides subsequent tips as long as the popover attribute equates to auto -->
<button popovertarget="onboardingTipA" popovertargetaction="hide">Cancel onboarding</button>

<ul>
  <li id="toolA">Tool A</li>
  <li id="toolB">Tool B</li>
  <li id="toolC">Another tool, “C”</li>
  <li id="toolD">Another tool — let’s call this one “D”</li>
</ul>

<!-- onboardingTipA’s button triggers onboardingTipB -->
<dialog anchor="toolA" id="onboardingTipA" popover>
  onboardingTipA <button popovertarget="onboardingTipB" popovertargetaction="show">Next tip</button>
</dialog>

<!-- onboardingTipB’s button triggers onboardingTipC -->
<dialog anchor="toolB" id="onboardingTipB" popover>
  onboardingTipB <button popovertarget="onboardingTipC" popovertargetaction="show">Next tip</button>
</dialog>

<!-- onboardingTipC’s button triggers onboardingTipD -->
<dialog anchor="toolC" id="onboardingTipC" popover>
  onboardingTipC <button popovertarget="onboardingTipD" popovertargetaction="show">Next tip</button>
</dialog>

<!-- onboardingTipD’s button hides onboardingTipA, which in-turn hides all tips -->
<dialog anchor="toolD" id="onboardingTipD" popover>
  onboardingTipD <button popovertarget="onboardingTipA" popovertargetaction="hide">Finish onboarding</button>
</dialog>
::backdrop {
  animation: 2s fadeInOut;
}

[popover] {
  margin: 0;
  align-self: anchor-center;
  left: calc(anchor(right) + 10px);
}
/*
After users have had a couple of
seconds to breathe, start the onboarding
*/
setTimeout(() => {
  document.querySelector("#onboardingTipA").showPopover();
}, 2000);

Breakdown: setTimeout() reveals the first tip after two seconds. A fade-in-fade-out animation runs on the backdrop and all subsequent backdrops. The main document is not made inert and the backdrop doesn't persist, so attention is drawn to the tips without feeling invasive. Each popover holds a button that triggers the next tip, chaining them into a fully HTML onboarding flow. Normally showing a popover closes other popovers, but not when it is triggered from inside another popover. Re-showing a visible popover rolls onboarding back to that step, and hiding a popover hides it and all subsequent popovers — apparently only when popover is auto. The behavior is not fully understood, but it enables "restart onboarding" and "cancel onboarding" buttons made in pure HTML, and tips can be cycled with esc and return.

Making popovers modal

To combine the HTML-ness of popover with the semantics of <dialog>, one JavaScript line makes the main document inert and the popovers modal:

document.querySelectorAll("dialog[popover]").forEach(dialog => dialog.addEventListener("toggle", () => document.body.toggleAttribute("inert")));

The popovers must come after the main document, or they become inert too:

<body>
  <!-- All of this will become inert -->
</body>

<!-- Therefore, the modals must come after -->
<dialog popover> ... </dialog>

Transition-enabled examples

Looking at these APIs together matters now that they are maturing — each has clear things it can, can't, should and shouldn't do.