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

CSS :not() selector - chọn element KHÔNG có class/attribute/type nhất định


Pseudo-class :not() loại trừ các element khớp với selector bên trong.

Cú pháp

selector:not(exclude-selector) { styles; }

Ví dụ 1: Loại trừ con trực tiếp

<!DOCTYPE html>
<html>
<head>
  <style>
    p { background: cornflowerblue; color: white; padding: 15px; margin: 10px 0; }
    p:not(div > p) { 
      background: khaki; color: blue; 
      font-size: 1.4em; font-style: italic; 
    }
  </style>
</head>
<body>
  <div>
    <p>P trong div - KHÔNG bị ảnh hưởng bởi :not(div > p)</p>
    <h3>Demo</h3>
  </div>
  <p>P ngoài div - ÁP DỤNG :not(div > p) - vàng, chữ xanh, nghiêng</p>
</body>
</html>

Ví dụ 2: Loại trừ class .parent

<style>
  div { margin: 2%; background: cadetblue; padding: 20px; height: 200px; }
  div:not(.parent) { box-shadow: inset 0 0 24px tomato; padding: 2%; }
  .parent { border: 4px ridge orange; }
  .one { background: lightgreen; border: 4px groove gray; }
  .two { height: 40px; margin: 5px 0; background: #fff3cd; border: 1px solid #ffeeba; }
</style>
<body>
  <div class="parent">
    <div class="one">
      <div class="two"></div>
      <div class="two"></div>
    </div>
    <div class="one"></div>
  </div>
</body>

Kết quả

  • Ví dụ 1: P ngoài div có style đặc biệt, P trong div giữ style mặc định
  • Ví dụ 2: Tất cả div KHÔNG có class .parent có box-shadow đỏ, .parent thì không

Các pattern hữu ích

  • :not(:first-child) - tất cả trừ cái đầu
  • :not([hidden]) - element không ẩn
  • input:not([type="hidden"]) - input trừ hidden
  • :not(.exclude, .also-exclude) - loại trừ nhiều selector (CSS Selectors Level 4)