Style Parent Elements Conditionally with the CSS :has() Selector

Style parents conditionally with the CSS :has() selector

For years CSS could only look down the tree: style a child depending on its parent, never the other way round. :has() changes that. .card:has(img) matches a card that contains an image, and the theme no longer needs PHP or JavaScript to add classes like has-thumbnail. Since Firefox 121 in December 2023, all major browsers support it.

Problem: Post cards need a two-column layout when they have a featured image and a single column without, a form should show its error state as a whole, and the page should not scroll while the mobile menu is open; today the theme adds classes for all of this in PHP and JavaScript.

Solution: Use :has() on the parent with a selector for the child or state, combine it with :not() for the opposite case, and keep a fallback where the layout must not break in older browsers.

Cards with and without an image

.post-card {
    display: grid;
    gap: 1rem;
}

.post-card:has(.post-card__image) {
    grid-template-columns: 12rem 1fr;
}

.post-card:not(:has(.post-card__image)) .post-card__title {
    font-size: 1.5rem;
}

The PHP template prints the image only if the post has one, and the CSS adapts. The single-column layout is the default, so a browser without :has() shows a working, simpler card.

Form states

.ha-field:has(:user-invalid) label {
    color: #b00020;
}

.ha-field:has(:user-invalid) .ha-field__hint {
    display: block;
}

.comment-form:has(:invalid) .form-submit .submit {
    opacity: 0.7;
}

:user-invalid matches a field only after the user has interacted with it, so an empty required field is not red when the page loads. Keep the submit button clickable: a disabled-looking button without explanation is worse than a message after clicking, and the browser shows the validation messages on submit anyway.

The page while a menu is open

html:has(.ha-nav[data-open="true"]) {
    overflow: hidden;
}

.wp-block-group:has(> .wp-block-image:only-child) {
    padding: 0;
}

The first rule replaces the JavaScript that added a class to <html> when the menu opened. The second removes the padding of a group that contains nothing but an image, a common wish with editor content.

Support and fallbacks

@supports selector(:has(*)) {
    .post-card:has(.post-card__image) {
        align-items: start;
    }
}

@supports selector() applies rules only where :has() works. Use it for enhancements that would look wrong half-applied.

NOTE: :has() is evaluated on every change of the DOM, so very broad selectors such as body:has(*:hover) can cost performance on large pages. Anchor it to a specific parent and a short child selector, as above. Other modern CSS for component layouts: container queries.