CSS :modal Pseudo-Selector Targets Modal Elements Directly

The CSS :modal pseudo-selector provides a way to select elements that are currently in a modal state. This approach helps developers avoid managing extra classes in JavaScript by offering a native method to detect modal elements.

Browser Support

  • Chrome and Edge: 105
  • Firefox: 103
  • Safari: 15.6

Two types of elements are currently classified as :modal:

  • Dialog elements that use the showModal method.
  • Elements that are in full-screen mode.

Practical Usage

For example, developers can set the scale of all <dialog> elements that are :modal.

Consider a demo where a <dialog> can be displayed in either "modal" or "non-modal" style. When the modal version is shown, it leverages the ::backdrop element provided by the top layer.

For the non-modal version, which does not include a ::backdrop, a fake one can be created using the ::before pseudo-element. This approach is lighter and avoids blurring the content behind the dialog. The :not selector can be combined with :modal to detect a non-modal <dialog>.

The pseudo-selector also works for elements in full-screen mode. For instance, a heading element constructed from spans will animate its child spans when the element enters full-screen mode.