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

ความแตกต่างระหว่าง Pseudo-class และ Pseudo-element ใน CSS


Pseudo-class (คลาสปลอม)

Pseudo-class แทนสถานะของ selector เช่น :hover, :active, :last-child เริ่มต้นด้วยเครื่องหมายโคลนเดี่ยว :

:pseudo-class{ attribute: /*value*/ }

Pseudo-element (องค์ประกอบปลอม)

Pseudo-element ใช้เลือกองค์ประกอบเสมือนจริง เช่น ::after, ::before, ::first-line เริ่มต้นด้วยเครื่องหมายโคลนคู่ ::

::pseudo-element{ attribute: /*value*/ }

ตัวอย่างที่ 1: Pseudo-class :hover

<!DOCTYPE html> <html> <head> <style> a:hover{    padding: 3%;    font-size:1.4em;    color: tomato;    background: bisque; } </style> </head> <body> <p>You're somebody else</p> <a href=#>Dummy link 1</a> <a href=#>Dummy link 2</a> </body> </html>

ตัวอย่างที่ 2: Pseudo-element ::after และ pseudo-class :last-child

<!DOCTYPE html> <html> <head> <style> p::after {    content: " BOOM!";    background: hotpink; } p:last-child {    font-size: 1.4em;    color: red; } </style> </head> <body> <p>Anymore Snare?</p> <p>Donec in semper diam. Morbi sollicitudin sed eros nec elementum. Praesent eget nisl vitaeneque consectetur tincidunt. Ut molestie vulputate sem, nec convallis odio molestie nec.</p> <p>Hit</p> <p>Pop</p> </body> </html>

สรุปความแตกต่าง: Pseudo-class เลือกองค์ประกอบที่มีอยู่แล้วตามสถานะ (hover, focus, nth-child) ส่วน Pseudo-element สร้างองค์ประกอบใหม่ที่ไม่มีใน HTML (before, after, first-letter, selection)