CSS Pseudo-classes: เลือก Element ตามสถานะพิเศษ
Pseudo-class keywords (ขึ้นต้นด้วย :) เลือก element ตาม state: :hover, :focus, :active, :visited, :first-child, :nth-child(), :not(), :checked, :disabled, :valid, :invalid ฯลฯ
โค้ดตัวอย่าง: Link States
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
a { font-size: 18px; font-weight: bold; }
a:link { color: rgb(17, 0, 255); } /* ยังไม่ได้เยี่ยมชม */
a:visited { color: rgb(128, 0, 107); } /* เยี่ยมชมแล้ว */
a:hover { color: rgb(255, 105, 243); } /* hover */
a:active { color: rgb(255, 153, 0); } /* กำลังคลิก */
</style>
</head>
<body>
<h1>Pseudo Class Example</h1>
<a href="#">This is some sample link text</a>
<h2>Hover, Click บนลิงก์เพื่อดู pseudo class ทำงาน</h2>
</body>
</html>
Pseudo-classes สำคัญ ( catégorisée)
| Category | Pseudo-classes |
|---|---|
| Link/State | :link, :visited, :hover, :active, :focus, :focus-visible, :focus-within |
| Structural | :first-child, :last-child, :nth-child(n), :nth-last-child(n), :only-child, :first-of-type, :last-of-type, :nth-of-type(n), :only-of-type |
| Form/Input | :checked, :disabled, :enabled, :required, :optional, :valid, :invalid, :in-range, :out-of-range, :read-only, :read-write, :placeholder-shown, :default |
| Language | :lang(en), :dir(ltr|rtl) |
| Logical | :not(selector), :is(selector), :where(selector), :has(selector) (CSS4) |
| Target | :target, :target-within |
:has() – The Game Changer (CSS4)
/* Parent selector! */
.card:has(img) { border: 2px solid gold; }
.form:has(input:invalid) { border-color: red; }
nav:has(> ul > li:last-child) { padding-right: 0; }
รองรับ Chrome 105+, Firefox 121+, Safari 15.4+ – เปลี่ยน paradigm การเขียน CSS
Specificity
Pseudo-class มี specificity = class (0,1,0) ยกเว้น :not() ใช้ specificity ของ argument ภายใน, :where() specificity = 0, :is() ใช้ specificity สูงสุดของ arguments