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

การทำความเข้าใจ CSS Selector และ Declarations


CSS selectors ใช้สำหรับเลือกองค์ประกอบ HTML โดยการจับคู่แต่ละองค์ประกอบของรูปแบบที่กำหนด เรากำหนดสไตล์โดยการประกาศคุณสมบัติและค่าของมันภายใน selector

ไวยากรณ์

ไวยากรณ์สำหรับการประกาศสไตล์ดังนี้:

Selector { property: value; }

CSS มี simple selectors, attribute selectors, pseudo-classes, pseudo-elements และการรวม selectors ผ่าน combinators มาตรฐาน ตารางต่อไปนี้แสดงรายการ selectors บางส่วน:

Selectorประเภท Selectorคำอธิบาย
*Universal selectorจับคู่ทุกองค์ประกอบ
eType selectorจับคู่ทุกองค์ประกอบแบบ e
e1e2Descendant selectorจับคู่องค์ประกอบ e2 ใดๆ ที่เป็นลูกหลานขององค์ประกอบ e1
e1>e2Child selectorจับคู่องค์ประกอบ e2 ใดๆ ที่เป็นลูกโดยตรงขององค์ประกอบ e1
e[bar="demo"]Attribute selectorจับคู่องค์ประกอบ e ใดๆ ที่แอตทริบิวต์ "bar" มีค่าเท่ากับ "demo" อย่างแน่นอน
#idID 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>

ผลลัพธ์

ได้ผลลัพธ์ดังนี้:

การทำความเข้าใจ CSS Selector และ Declarations

ตัวอย่างเพิ่มเติม

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

ผลลัพธ์

ได้ผลลัพธ์ดังนี้:

การทำความเข้าใจ CSS Selector และ Declarations