CSS Class Selector ใช้เลือก element ที่มี class="classname" เพื่อกำหนด style ให้กลุ่ม element พร้อมกัน
รูปแบบพื้นฐาน
.classname { property: value; }
ตัวอย่าง: Class แบบง่าย
<!DOCTYPE html>
<html>
<head>
<style>
.highlight { background: #ffff00; color: #000; }
</style>
</head>
<body>
<p>Normal text</p>
<p class="highlight">Highlighted text</p>
<p>Normal text</p>
</body>
</html>
ตัวอย่าง: Element-specific Class
h2.warning { color: red; font-weight: bold; }
<h2 class="warning">Warning!</h2> <p class="warning">This won't be red (only h2.warning)</p>
ตัวอย่าง: Multiple Classes
.device { background: #000; color: #fff; }
.accessories { text-align: center; font-size: 1.2em; }
<p class="device accessories">DEVICE DETAILS</p> <p class="device">Information about devices.</p>
Best Practices
- ชื่อ class ใช้ความหมาย (semantic):
.btn-primaryไม่ใช่.blue-button - ใช้ kebab-case:
.main-headerไม่ใช่.mainHeader - หลีกเลี่ยง ID selector (#id) สำหรับ styling (specificity สูงเกินไป)
- BEM methodology:
.block__element--modifier - Utility classes:
.text-center,.mt-4,.d-flex
Specificity
Class selector = 0, 1, 0 (ID=1,0,0, Element=0,0,1) Inline style = 1,0,0,0