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.

Join the discussionCome work with us
Share on Twitter
Bookmark this page
Ask a questionImprove this Answer

Related Answers

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

    TwitterGitHubDribbbleLinkedin
© 2023 • Sentry is a registered Trademark
of Functional Software, Inc.