Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

CSS :first-of-type Pseudo-Class คืออะไร?

บางครั้งเมื่อเขียน CSS เราต้องการ target element เฉพาะ สมมติมี HTML document เต็มไปด้วย <div> และ <span> tags แต่ต้องการ style เฉพาะตัวแรกของแต่ละ type เราสามารถทำได้ด้วย pseudo-class ชื่อ :first-of-type

Pseudo-class คือวิธีให้ CSS selector มี styles เฉพาะต่างจาก styles ตัวเดิม ขึ้นอยู่กับ state ของ element ในที่นี้ต้องการ select <div> แรก และ <span> แรก เพื่อ style – spans หรือ divs อื่นๆ จะไม่ถูก select

ตัวอย่างเพื่อเริ่มต้น:

<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>

ที่นี่มีชุดของ divs และ spans ภายใน divs CSS selector div:first-of-type select เฉพาะ element แรกของ type นั้นและ style มัน div span:first-of-type select span แรกในแต่ละ div เนื่องจาก div เป็น parent element

div:first-of-type เทียบเท่า div:nth-child(1)

สรุป

บทความนี้ดู pseudo-class :first-of-type เห็นว่า pseudo-class คือการอธิบาย state ที่ต้องการให้ CSS selector อยู่ตอน style ดู syntax แบบทั่วไป แนะนำดู pseudo-selectors อื่นๆ เพื่อเข้าใจเพิ่มเติม!