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

Selector (Bộ chọn) trong CSS là gì và cách sử dụng

Selector (Bộ chọn) là phần của CSS rule xác định **element HTML nào** sẽ được áp dụng style. Selector trỏ đến element, declaration block chứa các property-value.

Cấu trúc CSS Rule

selector {
  property: value;
  property: value;
}

Selector (Bộ chọn) trong CSS là gì và cách sử dụng

Ví dụ Type Selector

h1 {
  color: #36CFFF;
}

Các loại Selector chính

LoạiCú phápVí dụMô tả
Typetagnameh1, pChọn theo tên thẻ
Class.classname.btn, .cardChọn theo attribute class
ID#idname#header, #mainChọn theo attribute id (duy nhất)
Universal**Chọn tất cả element
Attribute[attr], [attr="val"][type="text"]Chọn theo attribute
Pseudo-class:state:hover, :first-childTrạng thái đặc biệt
Pseudo-element::element::before, ::first-linePhần ảo của element
Combinator , >, +, ~div p, ul > liMối quan hệ giữa element

Độ đặc hiệu (Specificity)

Inline style (1000) > ID (100) > Class/Attribute/Pseudo-class (10) > Type/Pseudo-element (1) > Universal (0).

Selector càng cụ thể → độ đặc hiệu cao hơn → ghi đè style selector chung hơn.