Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :target-within pseudo-class

Reference for the CSS :target-within pseudo-class: match an element that contains the URL target. Limited browser support, with a :has(:target) alternative.

The :target-within pseudo-class is meant to match an element that is the :target or contains the target. It is the fragment-link counterpart of :focus-within.

Limited support. At the time of writing, :target-within is not available in stable releases of the major browsers. Do not rely on it. Use :has(:target) instead, which is widely supported and does the same job for most cases.

CSS
.card:has(:target) {
  outline: 3px solid #f59e0b;
}

Try it

Container of the target, with :has()

Syntax

CSS
:target-within { /* declarations */ }

No arguments. Specificity would be (0,1,0). Matching would cover the element itself and its descendants, including across shadow boundaries.

Syntax and arguments

Part Description
:target-within Intended to match an element that is the target or has a descendant that is.
Detect support @supports selector(:target-within) { ... }
Alternative :is(:target, :has(:target)), or .wrapper:has(:target)

Usage notes

  • Feature-detect before using. Put rules inside @supports selector(:target-within), or write the :has(:target) version, which needs no detection in current browsers.
  • Why it is useful. A card, accordion section or table row can highlight itself when a link points to something inside it.
  • Fixed headers. As with :target, add scroll-margin-top so the destination is not hidden under sticky bars.
  • Do not use as the only cue. Highlighting is helpful, but the page should still make sense if the style does not apply.

Browser support

Not supported in stable versions of major browsers at the time of writing. Check current compatibility data before depending on it; use :has(:target) meanwhile.