Sentry Answers>CSS>

Is there a CSS parent selector?

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:

Click to Copy
<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:

Click to Copy
.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:

Click to Copy
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.

Further Reading

If you’re looking to get a deeper understanding of how web performance optimization works, take a look at the following articles:

  • Syntax.fmHasty Treat - CSS Grid Masonry (Grid Level 3)
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fmHasty Treat - CSS Grid Level 2 aka Subgrid
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

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