Hai khái niệm dễ nhầm lẫn nhưng hoàn toàn khác nhau về bản chất và cú pháp.
Pseudo-class (Lớp giả) - Dấu 2 chấm đơn :
Trạng thái của element: :hover, :active, :focus, :first-child, :nth-child(), :checked, :visited...
:pseudo-class { property: value; }
Pseudo-element (Phần tử giả) - Dấu 2 chấm kép ::
Tạo element ảo không có trong HTML: ::before, ::after, ::first-line, ::first-letter, ::placeholder, ::selection...
::pseudo-element { property: value; }
Ví dụ Pseudo-class: :hover
<style>
a:hover { padding: 3%; font-size: 1.4em; color: tomato; background: bisque; }
</style>
<a href="#">Dummy link 1</a> <a href="#">Dummy link 2</a>
Kết quả: Hover link → to lên, màu cam, nền cam nhạt.
Ví dụ Pseudo-element: ::after + :last-child
<style>
p::after { content: " BOOM!"; background: hotpink; }
p:last-child { font-size: 1.4em; color: red; }
</style>
<p>Anymore Snare?</p>
<p>Donec in semper diam...</p>
<p>Hit</p>
<p>Pop</p>
Kết quả: Mọi <p> thêm " BOOM!" hồng, <p> cuối cùng to đỏ.
Bảng so sánh
| Đặc điểm | Pseudo-class | Pseudo-element |
|---|---|---|
| Cú pháp | :name | ::name |
| Mục đích | Trạng thái element | Tạo content/phần tử ảo |
| Có trong DOM? | Có (element thật) | Không (chỉ render) |
| Content property | Không dùng | Cần content cho ::before/::after |
| Ví dụ | :hover, :first-child | ::before, ::placeholder |