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

ID Selector (Bộ chọn ID) trong CSS

ID Selector chọn element dựa trên attribute id (duy nhất trong document). Cú pháp: #idname.

Cơ bản

#black {
  color: #000000;
}

Áp dụng cho **mọi element** có id="black".

Chỉ định tag cụ thể (higher specificity)

h1#black {
  color: #000000;
}

Chỉ áp dụng cho <h1 id="black">. Specificity: (0, 1, 0, 1) = 101 (ID + Type).

Descendant Selector dựa trên ID (Sức mạnh thực sự)

#black h2 {
  color: #000000;
}

Tất cả <h2> **bên trong** element có id="black" sẽ màu đen. Pattern này rất phổ biến cho scope style theo component/section.

Lưu ý quan trọng

  • id phải **duy nhất** trong document. Dùng ID selector cho element duy nhất.
  • Specificity cao: (0, 1, 0, 0) = 100. Rất khó override (cần !important hoặc ID khác).
  • Khuyến nghị: **Hạn chế dùng ID cho styling**. Dùng Class cho reusable component. ID dành cho: anchor link (href="#section"), JS getElementById, ARIA aria-labelledby.
  • CSS Modules, BEM, Utility-first (Tailwind) tránh ID selector.