कभी-कभी जब हम अपना CSS बनाते हैं, तो हम एक निश्चित एलिमेंट को टारगेट करना चाहते हैं। मान लीजिए अगर हमारे पास <div> टैग्स और <span> टैग्स से भरा एक HTML डॉक्यूमेंट है, लेकिन हम केवल प्रत्येक टाइप के पहले को टारगेट करके उसे किसी तरह स्टाइल करना चाहते हैं। हम इसे :first-of-type स्यूडो-क्लास के साथ कर सकते हैं।
एक स्यूडो-क्लास एक CSS सेलेक्टर के लिए मूल स्टाइल्स से अलग स्पेसिफिक स्टाइल्स रखने का एक तरीका है। यह इस बात पर निर्भर करता है कि एलिमेंट किस स्टेट में है। इस उदाहरण में, हम पहले <div> और पहले <span> को सेलेक्ट करना चाहते हैं ताकि हम इसे स्टाइल कर सकें - कोई अन्य स्पैन या डिव सेलेक्ट नहीं होंगे।
यहां एक उदाहरण है जिससे आप शुरू कर सकते हैं:
<html> <head> <style> body { display: flex; flex-flow: row wrap; } div { height: 100px; width: 200px; border: 1px solid black; margin: 20px; padding: 20px; } /* First of type */ div:first-of-type { background: purple; color: white; } div span:first-of-type { color: red; text-decoration: underline; background: lightblue; } </style> </head> <body> <div>I am the first div<span> I am inside the div and the first span</span><span> I am the second span</span></div> <div>I am the second the div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the third div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the fourth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the fifth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the sixth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the seventh div<span> I am inside the div</span><span> I am the second span</span></div> </body> </html>
यहां हमारे पास डिव्स का एक सेट और उन डिव्स के अंदर स्पैन हैं। CSS सेलेक्टर div:first-of-type केवल उसके टाइप के पहले एलिमेंट को सेलेक्ट करता है और उसे स्टाइल करता है। div span:first-of-type प्रत्येक डिव में पहला स्पैन सेलेक्ट करता है क्योंकि डिव पैरेंट एलिमेंट है।
div:first-of-type div:nth-child(1) कहने के समान होगा।
निष्कर्ष
इस लेख में हमने :first-of-type स्यूडो-क्लास पर एक नज़र डाली। हमने देखा कि एक स्यूडो-क्लास मूल रूप से सिर्फ कुछ ऐसा है जो उस स्टेट का वर्णन करता है जिसमें हम CSS सेलेक्टर को स्टाइल करते समय चाहते हैं। हमने जनरल सिंटैक्स पर भी एक नज़र डाली। मैं अन्य स्यूडो-सेलेक्टर्स को देखने और उनके लिए एक फील पाने का सुझाव दूंगा!