पाठ 28 / 30

आधुनिक Selectors और Native Nesting

सभी modern browsers में समर्थित :is(), :where(), :has() और native nesting से छोटा CSS लिखें।

:is(), :where() और :has()

:is() selectors समूहित करता है, :where() वही करता है पर शून्य specificity के साथ, और :has() अपने children के आधार पर parent चुनता है।

:is(h1, h2, h3) a { text-decoration: none; }
:where(.btn, .link) { color: inherit; }        /* specificity 0 */

/* cards that contain an image */
.card:has(img) { padding-top: 0; }
/* a label whose input is invalid */
label:has(+ input:invalid) { color: crimson; }

Native nesting

CSS अब Sass के बिना nested rules support करता है। parent को दर्शाने के लिए & उपयोग करें।

.card {
  padding: 16px;
  & h3 { margin: 0; }
  &:hover { box-shadow: 0 4px 12px rgb(0 0 0 / 0.15); }
  @media (min-width: 768px) { padding: 24px; }
}

Specificity और पठनीयता नियंत्रण में रखने के लिए nesting को दो या तीन स्तर तक रखें।

त्वरित जाँच

त्वरित जाँच: कौन-सा selector अपने children के आधार पर parent चुनता है?

  • :has()
  • :is()
  • :where()
  • :root
Answer

:has() — :has() संबंधपरक "parent" selector है।