📝

CSSで特定の要素を含む場合や特定の要素を含むがある要素は含まない場合

2023/03/18に公開

想定

以下のようなページの想定

<div class="class-name">
  <a title="none" href="https://example.com"></a>
  <div></div>
  <div>
    <div class="need-display-class"></div>
  </div>
</div>

子要素に特定の要素を含む場合

疑似クラスの:has()を使用
https://developer.mozilla.org/ja/docs/Web/CSS/:has

.class-name:has(a[title="none"])
{
  display: none;
}

子要素に特定の要素を含むかつ、特定の要素は含まない場合

:has()と:not()を組合せ
https://developer.mozilla.org/ja/docs/Web/CSS/:not

.class-name:has(a[title="none"]):not(:has(div[class="need-display-class"]))
{
  display: none;
}

Discussion