CSS selectors ใช้สำหรับเลือกองค์ประกอบ HTML โดยการจับคู่แต่ละองค์ประกอบของรูปแบบที่กำหนด เรากำหนดสไตล์โดยการประกาศคุณสมบัติและค่าของมันภายใน selector
ไวยากรณ์
ไวยากรณ์สำหรับการประกาศสไตล์ดังนี้:
Selector { property: value; }
CSS มี simple selectors, attribute selectors, pseudo-classes, pseudo-elements และการรวม selectors ผ่าน combinators มาตรฐาน ตารางต่อไปนี้แสดงรายการ selectors บางส่วน:
| Selector | ประเภท Selector | คำอธิบาย |
|---|---|---|
| * | Universal selector | จับคู่ทุกองค์ประกอบ |
| e | Type selector | จับคู่ทุกองค์ประกอบแบบ e |
| e1e2 | Descendant selector | จับคู่องค์ประกอบ e2 ใดๆ ที่เป็นลูกหลานขององค์ประกอบ e1 |
| e1>e2 | Child selector | จับคู่องค์ประกอบ e2 ใดๆ ที่เป็นลูกโดยตรงขององค์ประกอบ e1 |
| e[bar="demo"] | Attribute selector | จับคู่องค์ประกอบ e ใดๆ ที่แอตทริบิวต์ "bar" มีค่าเท่ากับ "demo" อย่างแน่นอน |
| #id | ID selector | จับคู่องค์ประกอบที่มี ID เท่ากับ "id" |
ตัวอย่าง
ตัวอย่างต่อไปนี้แสดง CSS selectors:
<!DOCTYPE html> <html> <head> <style> p::first-line { background-color: lightgreen; color: white; text-decoration: overline black; } </style> </head> <body> <h2>หัวข้อสาธิต</h2> <p>This is our demo text. Only the first line will have a different style. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </p> </body> </html>
ผลลัพธ์
ได้ผลลัพธ์ดังนี้:

ตัวอย่างเพิ่มเติม
<!DOCTYPE html> <html> <head> <style> p::first-line { background-color: lightgreen; color: white; text-decoration: overline red; } span { font-size: 1.4em; } #demo { box-shadow: inset 0 0 20px orange; } </style> </head> <body> <h2>รายละเอียดนักศึกษา</h2> <p><span>Student</span>details would be mentioned here. <span id="demo">Student Marks</span> includes the score of students in the final semester held July 2018. With that the ranks are also displayed.</p> </body> </html>
ผลลัพธ์
ได้ผลลัพธ์ดังนี้:
