กฎ !important ใช้เพื่อลบล้าง (override) การจัดรูปแบบของเว็บเพจ ตรงๆบอกเลยว่ามีเหตุผล ไม่ควรใช้ !important มากกว่าเหตุผลที่ควรใช้ มาเข้าใจการใช้งานและทำไมควรใช้ขั้นต่ำ
1. ลบล้าง User-agent Stylesheets (เช่น Bootstrap)
เมื่อเขียน CSS บางครั้งต้องลบล้าง stylesheet ที่มีมาให้ เช่น ใช้ CSS framework เช่น Bootstrap ต้องการปรับแต่งสไตล์ที่ built-in
<!DOCTYPE html> <html lang="en"> <head> ... <link rel="stylesheet" href="bootstrap.min.css"> <style> .nav { color: black; background-color: pink; } </style> </head> <body> ... <nav class="navbar navbar-expand-lg navbar-light bg-light">...</nav> </body> </html>
ใน selector .navbar ให้เพิ่ม !important หลังค่าสีพื้นหลัง:
.nav { color: black; background-color: pink !important; }
รันใหม่ — สีพื้นหลัง navbar จะเปลี่ยน นี่คือ use case แรก: ใช้ !important ลบล้างสไตล์จาก CSS framework
2. ลบล้าง Inline Styles
กรณีอื่นคือต้องลบล้าง inline styles ของ元素
<style> .line-item:first-child{ color: purple; } .line-item:last-child { color: crimson; font-size: xx-large; font-variant: normal; } </style> ... <li class="line-item" style="color: rosybrown; font-size: large;">Rose Tyler</li> <li class="line-item" style="color:royalblue; font-size: larger; font-variant:small-caps;">The Doctor</li>
ใช้ !important ใน CSS เพื่อลบล้าง inline styles
ข้อควรระวัง: !important ไม่ใช่ best practice ควรใช้น้อยที่สุด เพราะอาจทำให้หาบั๊กยากในภายหลัง หากไม่ได้ใช้ framework มักจัดเรียง selector ใหม่ได้เพื่อให้ผลลัพธ์เหมือนกันโดยไม่ต้องใช้ !important
สรุป
!important มีประโยชน์ในบางสถานการณ์ (override framework, inline styles) แต่ควรใช้ขั้นต่ำและเป็นอันสุดท้าย เพราะทำให้ความเฉพาะเจาะจง (specificity) ซับซ้อนและดูแลรักษายาก