Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Quy tắc ghi đè (Override) Style Sheet Rule trong CSS

Khi nhiều rule CSS áp dụng cho cùng element, trình duyệt quyết định rule nào thắng theo **Cascade (Thác nước)**. Thứ tự ưu tiên từ cao đến thấp:

  1. Inline style (style="..." attribute)
    • Specificity: 1000 (cao nhất).
    • Ghi đè mọi rule trong <style> và external stylesheet.
  2. Embedded/Internal style (<style>...</style> trong <head>)
    • Ghi đè rule trong external stylesheet (nếu specificity bằng nhau).
    • Vị trí trong <head>: viết sau <link> thì thắng.
  3. External stylesheet (<link rel="stylesheet">)
    • Ưu tiên thấp nhất (nếu specificity bằng nhau).
    • Áp dụng khi 2 rule trên không áp dụng.

Quan trọng: Specificity (Độ đặc hiệu) quan trọng hơn vị trí

Rule với selector cụ thể hơn (specificity cao hơn) **luôn thắng** bất kể viết ở đâu.

SelectorSpecificityVí dụ
Inline style1000style="color: red"
ID selector100#header
Class / Attribute / Pseudo-class10.btn, [type="text"], :hover
Type / Pseudo-element1h1, ::before
Universal0*

!important

p { color: red !important; }
  • Bắt buộc rule thắng (trừ inline style cũng có !important).
  • Khuyến nghị: Hạn chế tối đa. Làm debug khó, phá vỡ cascade tự nhiên.
  • Chỉ dùng cho: Utility class (Tailwind), override third-party library không thể sửa.

Tóm tắt thứ tự thắng

  1. Inline style + !important
  2. Inline style
  3. External/Embedded + !important
  4. Selector specificity cao hơn
  5. Source order (viết sau thắng) khi specificity bằng nhau