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/
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>
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
Definitely yes, you can do it by chaining two different selectors:
Is the last child of it's type.
.container > .widget-button:nth-child(1):last-child
Edit: Apparently I misunderstood the question, but this can be helpful in some other cases.
.wrapper {
margin: 50px 0;
padding: 0 10px;
border: 1px solid #555;
}
.wrapper div {
border: 1px solid #555;
padding: 0px 5px 10px 5px;
margin: 10px 0;
}
.wrapper div:not(:first-child:last-child) {
background-color: gold;
}
<div class="wrapper">
<div class="container">Container #1</div>
<div class="container">Container #2</div>
<div class="container">Container #3</div>
<div class="container">Container #4</div>
<div class="container">Container #5</div>
</div>
<div class="wrapper">
<div class="container">Container #1</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With