CSS Pseudo Classes เป็นการแทนสถานะพิเศษขององค์ประกอบต่างๆ คลาสเหล่านี้ไม่ได้แทนองค์ประกอบพื้นฐานในเอกสารเท่านั้น แต่ยังรวมถึงปัจจัยภายนอกเช่น สถานะ ตำแหน่ง ประวัติ ฯลฯ ด้วย การใช้ pseudo classes เหล่านี้ นักพัฒนาสามารถจัดสไตล์องค์ประกอบที่ไม่สามารถเลือกได้โดยตรงผ่าน CSS selectors
ไวยากรณ์
ไวยากรณ์ของการใช้ CSS Pseudo classes บนองค์ประกอบมีดังนี้:
Selector:pseudo-class { css-property: /*value*/; }
ตัวอย่าง
ลองดูตัวอย่างการใช้งาน CSS Pseudo Classes:
<!DOCTYPE html> <html> <head> <title>CSS Pseudo Class</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input:valid { color: #fefefe; background-color: #4CAF50; } input:invalid { color: #fefefe; background-color: #DC3545; } </style> </head> <body> <form> <fieldset> <legend>CSS Pseudo Class</legend> <label for="EmailSelect">Email : <input type="email" id="EmailSelect" size="25" required> </label><br> <label for="PassSelect">Password : <input type="password" id="PassSelect" minlength="8" required> </label> <div id="divDisplay">Min. Strength of Password: 8<br>Both Fields are Required</div> </fieldset> </form> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:
เมื่อฟิลด์ฟอร์มมีข้อมูลไม่ถูกต้อง:

เมื่อฟิลด์ฟอร์มมีข้อมูลถูกต้อง:

ตัวอย่าง
ลองดูตัวอย่างเพิ่มเติมของ CSS Pseudo classes:
<!DOCTYPE html> <html> <head> <title>CSS Pseudo Class</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } a { text-decoration: none; background:grey; color: white; border-radius: 3px; padding: 6px; } input[type="button"] { border-radius: 10px; } :target { border:4px solid black; margin: 0 auto; height: 200px; width: 200px; background-image: url('https://www.tutorialspoint.com/arangodb/images/arangodb-mini-logo.jpg'); } #circle { border-radius: 50%; } </style> </head> <body> <form> <fieldset> <legend>CSS Pseudo Class</legend> <div> <div id="circle"></div> <div id="square"></div> </div> <div> <a href="#square">Tile</a> <a href="#circle">Avatar</a> </div> </fieldset> </form> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้:
ก่อนคลิกปุ่มใดๆ:

หลังคลิกปุ่ม 'Tile':

หลังคลิกปุ่ม 'Avatar':
