Reputation: 689
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
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 childThe second selector is optional - in case you just have a button without the boat div
Upvotes: 1
Reputation: 21
To get the button red inside of the boat div you can use the selector:
.parent > .boat > .test {
}
Upvotes: 1