I'm playing around with CSS selectors and i'm wondering can i build a custom css selector to only work when there only one of class .widget-button
, example code;
<div class='container a'>
<div class='widget-a' />
<div class='widget-b' />
<div class='widget-button' />
<div class='widget-b' />
</div>
So you would assume theres' a combination of pseudo selectors (:only-child ?
) to this job that will work for the above? Hoever the bellow example should no selections/styles applyied as there more then one that class.
<div class='container b'>
<div class='widget-a' />
<div class='widget-b' />
<div class='widget-button' />
<div class='widget-z' />
<div class='widget-x' />
<div class='widget-button' />
<div class='widget-z' />
</div>
Here a JSFiddle
https://jsfiddle.net/2L593m3x/
can i build a custom css selector to only work when there only one of class
Long story short: No.
We keep getting questions here about how to select nth-of-class
.
You cannot select nth-of-class
.
You can select by children.
You can select by element type.
You cannot select by element class.
At some point, nth-match
(and complementary selectors) may arrive:
e.g.
.widget-button:nth-match(2n+1)
.widget-button:first-match
.widget-button:last-match
.widget-button:only-match
If you are fine with creating custom tags (or whenever Web Components gets widespread support), you could use :only-of-type
:
div>* {
display: inline-block;
width: 16px;
height: 16px;
background-color: red;
}
widget-button:only-of-type {
background-color: blue;
}
<div>
<widget-a></widget-a>
<widget-b></widget-b>
<widget-button></widget-button>
<widget-b></widget-b>
</div>
<div>
<widget-a></widget-a>
<widget-b></widget-b>
<widget-button></widget-button>
<widget-z></widget-z>
<widget-x></widget-x>
<widget-button></widget-button>
<widget-z></widget-z>
</div>
only one child in parent:
p:has(br:first-child:last-child)
bonus
p:has(br:only-child)
Definitely yes, you can do it by chaining two different selectors:
Edit: Apparently I misunderstood the question, but this can be helpful in some other cases.