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

Time:12-20

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 >
    <div >
        <div ></div>
        <div ></div>
    </div>

    <div ></div>

    <div >
        <div >
            ::before
        </div>
    </div>
</div>

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

CodePudding user response:

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.

CodePudding user response:

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

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

  <div >bbb</div>

  <div >
    <div >
      ccc
    </div>
  </div>
</div>

CodePudding user response:

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