Ruby
Ruby

Reputation: 153

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

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

Upvotes: 4

Views: 817

Answers (3)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

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>

Upvotes: 1

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

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{
    ... 
}

Upvotes: 0

PuroGrammer
PuroGrammer

Reputation: 121

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.

Upvotes: 0

Related Questions