Is there a CSS parent selector?

Matthew C.

The Problem

You want to select the parent of an element to style it. For example, you may have the following two buttons and you want to add extra padding to the button that has an icon:

<button class="btn"> Start game <span class="icon"> &#129409; </span> </button> <button class="btn"> High Scores </button>

You need to select the parent button of the span with a class of "icon". How do you do this?

The Solution

You can use the :has() CSS pseudo-class to select a parent element.

The :has() pseudo-class takes a selector or list of selectors as an argument. Add the :has() pseudo-class to an element to select it only if it contains an element that matches the passed-in selector argument.

For example, the CSS code below adds padding to the button with a class of "btn" if it has an element with a class of "icon" inside it:

.btn:has(.icon) { padding: 0.25rem 0.5rem; }

The browser support for the :has() selector is quite good; most major browsers support it.

Alternatively, you can use JavaScript to select a parent element and style it:

const icon = document.querySelector('.btn .icon'); const btn = icon.parentNode; btn.style.padding = "0.25rem 0.5rem";

You first select the child element and then get its parent element using the parentNode property.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.