Quy tắc !important trong CSS
Quy tắc !important cho phép **ghi đè độ ưu tiên (specificity)** của CSS, buộc một khai báo luôn được áp dụng bất kể vị trí hoặc độ đặc hiệu của selector.
Cú pháp
selector {
property: value !important;
}
Ví dụ cơ bản
<style>
/* Không có !important - quy tắc sau ghi đè quy tắc trước */
p { color: #ff0000; } /* Đỏ */
p { color: #000000; } /* Đen - thắng vì cùng specificity, viết sau */
/* Có !important - quy tắc đầu luôn thắng */
p { color: #ff0000 !important; } /* Luôn ĐỎ */
p { color: #000000; } /* Bị bỏ qua */
</style>
<p>Tutorialspoint.com - Văn bản này sẽ màu ĐỎ</p>
Thứ tự ưu tiên CSS (Cascade) - Từ cao đến thấp
- User agent stylesheet (trình duyệt mặc định)
- User stylesheet (người dùng tùy chỉnh)
- Author stylesheet (dev viết)
- External stylesheet
- Internal stylesheet (<style>)
- Inline style (style="...")
- Author !important
- User !important
- User agent !important
Lưu ý: !important của author (dev) thắng over inline style, nhưng thua user !important (hiếm gặp).
Khi nào NÊN dùng !important
- Ghi đè style từ **thư viện/framework bên thứ 3** (Bootstrap, Material UI...) không thể sửa source
- Utility classes bắt buộc:
.hidden { display: none !important; } - Email HTML (client email hỗ trợ CSS kém, cần !important để đảm bảo)
- Print stylesheet:
@media print { .no-print { display: none !important; } } - Testing/debug nhanh (xóa sau khi xong)
Khi nào KHÔNG NÊN dùng !important
- CSS thông thường của dự án - gây khó bảo trì, debug
- Khi có thể tăng specificity selector (VD:
.parent .childthay vì.child !important) - Trong component-based architecture (React, Vue) - dùng CSS Modules, Styled Components tránh conflict
Mẹo debug !important
/* DevTools: Tìm tất cả !important trong CSS */
* {
/* Không có cách CSS thuần túy để detect */
}
/* JavaScript detect */
document.querySelectorAll('*').forEach(el => {
const styles = getComputedStyle(el);
for (let prop of styles) {
if (styles.getPropertyPriority(prop) === 'important') {
console.log(el, prop, styles.getPropertyValue(prop));
}
}
});