Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

กฎ !important ใน CSS: บังคับความสำคัญสูงสุด


กฎ !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 StylesheetDefault browser styles
2User StylesCustom user stylesheet
3Author Styles (Normal)CSS ของเรา
4Author Styles !importantcolor: red !important
5User Styles !importantUser override
6 (สูงสุด)Inline style + !importantstyle="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; }