परिचय
CSS में :nth-child(odd) और :nth-child(even) स्यूडो-क्लासेस का उपयोग करके वैकल्पिक एलिमेंट्स को स्टाइल किया जा सकता है बिना जावास्क्रिप्ट के। यह शुद्ध CSS समाधान जावास्क्रिप्ट से अधिक कुशल है।
उदाहरण
<!DOCTYPE html> <html lang="hi"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ऑड/ईवन क्लास</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <section class="subjects"> <article class="subjectName">MongoDB</article> <article class="subjectName">Javascript</article> <article class="subjectName">Java</article> <article class="subjectName">MySQL</article> </section> <style> .subjectName:nth-child(odd) { color: blue; } .subjectName:nth-child(even) { color: purple; } </style> </body> </html>
आउटपुट

चलाने के निर्देश
उपरोक्त प्रोग्राम को चलाने के लिए, फ़ाइल का नाम anyName.html (index.html) सेव करें और फ़ाइल पर राइट-क्लिक करके VS कोड एडिटर में "Open with Live Server" विकल्प चुनें।
जावास्क्रिप्ट विकल्प (यदि आवश्यक हो)
// यदि किसी कारण से JS आवश्यक हो
document.querySelectorAll('.subjectName').forEach((el, index) => {
el.classList.add(index % 2 === 0 ? 'odd' : 'even');
});
अन्य उपयोगी स्यूडो-क्लासेस
:nth-child(3n)- हर तीसरा एलिमेंट:nth-child(2n+1)- ऑड (1, 3, 5...):first-child,:last-child:nth-of-type()- विशिष्ट टाइप के एलिमेंट्स के लिए