Skip to main content

:has selector

Now (May, 2023), almost the modern browsers are supporting :has selector of CSS. This selector is very useful when you want to style related with children/parent elements.

Examples

Change field row state that has error field

If you use :has selector, you can change styles that has something specified element. so, for example, you can change the color of field row that has error field.

.c-form {
max-width: 320px;

&__row {
padding: 1rem;
}

&__label {
display: block;
}

&__field {
border: 1px solid #aaa;
color: #333;
background: #fff;

&.has-error {
border-color: #f00;
}
}

&__row:has(&__field.has-error) {
background: #fdd;
}
&__row:has(&__field.has-error) &__label {
color: #f00;
}
}

Change sibling element's style by hover action

When you want to change the sibling elements styles, it was needed to use JavaScript. But, if you use :has selector, it's able to implement by CSS only.

.c-grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
flex-grow: 1;
max-width: 320px;

&__item {
background: #ccc;
aspect-ratio: 1 / 1;
transition: opacity .3s;
}

&:has(&__item:hover) &__item:not(:hover) {
opacity: .6;
}
}