#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 42 of 49medium

What is the :has() Selector?

Understanding the parent selector in CSS.

What You'll Learn

  • :has() syntax
  • Selecting parents
  • Use cases

Syntax

styles.cssCSS
/* Select parent that contains child */
parent:has(child) { }

Examples

styles.cssCSS
/* Card with image gets different style */
.card:has(img) {
  padding-top: 0;
}

/* Form with invalid input */
form:has(input:invalid) {
  border-color: red;
}

/* Figure with figcaption */
figure:has(figcaption) {
  border: 1px solid #ddd;
}

Advanced Usage

styles.cssCSS
/* Previous sibling (has next sibling) */
li:has(+ li) {
  border-bottom: 1px solid #ddd;
}

/* Select label when checkbox is checked */
label:has(input:checked) {
  font-weight: bold;
}

/* Page has modal open */
body:has(.modal.open) {
  overflow: hidden;
}