: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.
- SCSS
- HTML
.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;
}
}
<div class="c-form">
<div class="c-form__row">
<label class="c-form__label">Don't have error</label>
<input type="text" class="c-form__field" />
</div>
<div class="c-form__row">
<label class="c-form__label">Have error *</label>
<input type="text" class="c-form__field has-error" />
</div>
</div>
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.
- SCSS
- HTML
.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;
}
}
<div class="c-grid">
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
<div class="c-grid__item"></div>
</div>