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

Pseudo-classes và CSS Classes

CSS Pseudo-classes có thể được kết hợp với CSS classes thay vì trực tiếp với các phần tử để cung cấp cách tiếp cận chọn lọc (selective) hơn cho một phần tử HTML.

Ví dụ 1: Kết hợp :lang() pseudo-class với class và ::after

<!DOCTYPE html>
<html>
<head>
<style>
  div { margin: 10px; padding: 10px; text-align: center; border: 1px solid black; }
  .Italy:lang(it)::after { padding: 20px; content: '~ Italy'; font-style: italic; }
  .Spain:lang(es)::after { padding: 8px; content: '~ Spain'; font-style: italic; }
  .Germany:lang(nl)::after { padding: 20px; content: '~ Belgium'; font-style: italic; }
  .Spain:lang(es) { background-image: linear-gradient(red 25%, yellow 25%, yellow 75%, red 75%); }
  .Italy:lang(it) { background-image: linear-gradient(90deg, #00ae00 33.3%, white 33.3%, white 66.6%, red 66.6%); }
  .Germany:lang(nl) { background-image: linear-gradient(90deg, black 33.3%, yellow 33.3%, yellow 66.6%, red 66.6%); }
</style>
</head>
<body>
  <div class="Italy" lang='it'>Rome</div>
  <div class="Germany" lang='nl'>Brussels</div>
  <div class="Spain" lang='es'>Madrid</div>
</body>
</html>

Kết quả

Pseudo-classes và CSS Classes

Ví dụ 2: :nth-child() kết hợp với class

<!DOCTYPE html>
<html>
<head>
<style>
  form { width: 70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; margin: 5px; box-sizing: border-box; }
  input[type="button"] { border-radius: 10px; }
  .child { display: inline-block; height: 40px; width: 40px; color: white; border: 4px solid black; }
  .child:nth-child(1) { background-color: #FF8A00; }
  .child:nth-child(2) { background-color: #F44336; }
  .child:nth-child(3) { background-color: #C303C3; }
  .child:nth-child(4) { background-color: #4CAF50; }
  .child:nth-child(5) { background-color: #03A9F4; }
  .child:nth-child(6) { background-color: #FEDC11; }
</style>
</head>
<body>
  <form>
    <fieldset>
      <legend>CSS Pseudo Classes and CSS Classes</legend>
      <div id="container">
        <div class="child"></div><div class="child"></div><div class="child"></div>
        <div class="child"></div><div class="child"></div><div class="child"></div>
      </div><br>
    </fieldset>
  </form>
</body>
</html>

Kết quả

Pseudo-classes và CSS Classes

Ý tưởng chính: Kết hợp class selector với pseudo-class cho phép:

  • Định dạng trạng thái cụ thể của một class (ví dụ: .btn:hover, .card:focus)
  • Chọn phần tử dựa trên vị trí trong nhóm cùng class (.item:nth-child(odd))
  • Kết hợp với attribute selector (.lang:lang(vi))
  • Tạo design system nhất quán (component states)

Pattern phổ biến:

.button { /* base styles */ }
.button:hover { /* hover state */ }
.button:active { /* active state */ }
.button:focus-visible { /* keyboard focus */ }
.button:disabled { /* disabled state */ }
.button.primary { /* variant */ }
.button.primary:hover { /* variant hover */ }