yeppe
yeppe

Reputation: 689

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>

Upvotes: 1

Views: 3464

Answers (2)

Pete
Pete

Reputation: 58432

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

Upvotes: 1

Benedikt Zoller
Benedikt Zoller

Reputation: 21

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

.parent > .boat > .test {
}

Upvotes: 1

Related Questions