How can I target a child class only if the first child has a specific class?

Viewed 169

How can I target the ::before in the class .child-ccc only if the first child has the class .hovered?

Here is the HTML output:

<div class="parent">
    <div class="child hovered">
        <div class="child-aaa"></div>
        <div class="child-aaa"></div>
    </div>

    <div class="child"></div>

    <div class="child-c">
        <div class="child-ccc">
            ::before
        </div>
    </div>
</div>

I have tried .child:first-child.hovered + .child-c .child-ccc:before

3 Answers

The + selector only selects adjacent siblings but child-c isn't. So, you have to use ~.

.parent .child:first-child.hovered~.child-c .child-ccc::before {
  content: '';
  display: block;
  height: 1rem;
  background-color: purple;
}
<div class="parent">
  <div class="child hovered">
    <div class="child-aaa">aaa</div>
    <div class="child-aaa">aaa</div>
  </div>

  <div class="child">bbb</div>

  <div class="child-c">
    <div class="child-ccc">
      ccc
    </div>
  </div>
</div>

Yes, You can achieve this by using advance CSS selectors. Try this code .child.hovered ~ .child-c > child-ccc::before This symbol ~ means the sibling of .child.hovered class and > means direct child element.

Selector + is adjacent sibling combinator it means if we write img + p it selects Paragraphs that come immediately after any image and the selector ~ is General sibling combinator it means if we use img ~ p it selects Paragraphs that are siblings of and subsequent to any image.

so in your problem instead of + you should use ~ to achieve your goal like this:

.child.hovered ~ .child-c .child-ccc::before{
    ... 
}
Related