简体   繁体   中英

CSS selector to select a child in the parent's hierarchy

Using css selectors I want to set the background of the button as red if it is the only button present in the hierarchy of .parent class.

I tried the below selector but it fails if the sibling of the button is inside a div.

<style> 
.parent  .test:only-of-type {
    background: red;
}
</style>

Case1: no button should be marked red (selector fails in this case)

 <div class="parent">
      <div class="boat">
        <button class="test">This is a paragraph.</button>
      </div>
      <button class="test">This is a paragraph.</button>
     <button class="test">This is a paragraph.</button>
      <div class="other">
        <button class="test">This is a paragraph.</button>
      </div>
    </div>
 </div>

Case2: button should be marked red

 <div class="parent">
      <div class="boat">
        <button class="test">This is a paragraph.</button>
      </div>
   </div>
 </div>

Case3: no button should be marked red (selector fails in this case)

 <div class="parent">
      <div class="boat">
        <button class="test">This is a paragraph.</button>
      </div>
      <div class="other">
        <button class="test">This is a paragraph.</button>
      </div>
    </div>
 </div>

To get the button red inside of the boat div you can use the selector:

.parent > .boat > .test {
}

You could use the :only-child selector:

 .parent > .boat:only-child > .test:only-child, .parent > .test:only-child { color: red; } 
 <div class="parent"> <div class="boat"> <button class="test">not red.</button> </div> <div class="other"> <button class="test">not red.</button> </div> </div> <div class="parent"> <div class="boat"> <button class="test">not red.</button> </div> <button class="test">not red.</button> <button class="test">not red.</button> <div class="other"> <button class="test">not red.</button> </div> </div> <div class="parent"> <div class="boat"> <button class="test">red.</button> </div> </div> 

Update

Selector explained:

  • .parent - start with your parent
  • > .boat:only-child greater than ( > ) means direct child so this means that .boat has to be a direct child of .parent and the only child (this is the :only-child bit)
  • > .test:only-child again this means that .test has to be a direct child of .boat and the only child

The second selector is optional - in case you just have a button without the boat div

More info on only-child

More info on direct child

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM