กฎ !important
กฎ !important ทำให้คุณสมบัติ CSS นั้นมี ความสำคัญสูงสุด จะถูกนำไปใช้เสมอ ไม่ว่าจะอยู่ที่ไหนในเอกสาร CSS จะชนะ specificity ทุกอย่าง
ตัวอย่าง: ถ้าไม่มี !important
<style>
p { color: #ff0000; } /* แดง */
p { color: #000000; } /* ดำ - ชนะเพราะอยู่หลัง */
</style>
<p>ข้อความนี้จะเป็นสีดำ</p>
ตัวอย่าง: ใช้ !important
<html>
<head>
<style>
p { color: #ff0000 !important; } /* แดง - ชนะเสมอ */
p { color: #000000; } /* ดำ - แพ้ */
</style>
</head>
<body>
<p>Tutorialspoint.com</p> /* จะเป็นสีแดง */
</body>
</html>
ลำดับความสำคัญ (Cascade Priority) - จากต่ำไปสูง
| ลำดับ | แหล่งที่มา | ตัวอย่าง |
|---|---|---|
| 1 (ต่ำสุด) | User Agent Stylesheet | Default browser styles |
| 2 | User Styles | Custom user stylesheet |
| 3 | Author Styles (Normal) | CSS ของเรา |
| 4 | Author Styles !important | color: red !important |
| 5 | User Styles !important | User override |
| 6 (สูงสุด) | Inline style + !important | style="color: red !important" |
เมื่อไหร่ควรใช้ !important
- Override inline styles จาก JavaScript/Framework
- Utility classes ที่ต้องชนะเสมอ (เช่น
.hidden { display: none !important; }) - Print stylesheet
- Testing/Debugging ชั่วคราว
❌ เมื่อไหร่ไม่ควรใช้
- ใช้แทนการเขียน selector ให้ specific พอ
- ใช้ทั่วไปในโปรเจกต์ (ทำให้ maintenance ยาก)
- Override library styles (ควรใช้ specificity หรือ build-time modification)
Best Practice
/ แทนที่จะเขียน /
.btn { background: blue !important; }
/ ควรเพิ่ม specificity /
.button.btn { background: blue; }
/* หรือ */
#app .btn { background: blue; }
/* หรือใช้ attribute selector */
.btn[class] { background: blue; }