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

Các bộ chọn nâng cao (Advanced Selectors) trong CSS


CSS có nhiều bộ chọn mạnh mẽ ngoài class/id cơ bản:

Các loại bộ chọn nâng cao

Bộ chọnCú phápMô tả
Adjacent Siblingh1 + pElement p ngay sau h1 (cùng parent)
General Siblingh1 ~ pTất cả p sau h1 (cùng parent)
Direct Childdiv > spanspan là con trực tiếp của div
Attributea[href="..."]Element có attribute khớp
:nth-of-type(n)ul:nth-of-type(1)Element loại đó thứ n
:not():not(.class)Loại trừ selector

Ví dụ

<html>
<head>
  <style>
    #red { color: red; }
    .green { background: green; }
    ul:nth-of-type(1) { background: rgb(0, 174, 255); }
    ul + h3 { border: 4px solid rgb(19, 0, 128); }
    a[href="https://www.wikipedia.org"] { font-size: 25px; }
    h1 ~ h3 { font-size: 40px; }
    div > span { background-color: DodgerBlue; color: white; padding: 2px 6px; }
  </style>
</head>
<body>
  <h1>Advanced Selectors Example</h1>
  <ul><li>Cow</li><li>Dog</li><li>Cat</li></ul>
  <ul><li>Puma</li><li>Leopard</li><li>Cheetah</li></ul>
  <h3>Animals</h3>
  <div>
    <span>Text sample</span>
    <p> Paragraph Text <span>span text</span> </p>
    <p class="green">Paragraph Text</p>
    <p id="red">Paragraph Text.</p>
    <p class="green">Paragraph Text</p>
  </div>
  <a href="https://www.google.com">www.google.com</a>
  <a href="https://www.wikipedia.org" target="_blank">www.wikipedia.org</a>
</body>
</html>

Kết quả giải thích

  • ul:nth-of-type(1): UL đầu tiên nền xanh dương
  • ul + h3: h3 ngay sau UL đầu tiên có viền tím
  • a[href="wikipedia.org"]: Link Wikipedia chữ to 25px
  • h1 ~ h3: Tất cả h3 sau h1 chữ 40px
  • div > span: Span con trực tiếp div nền xanh DodgerBlue