Selector for when only one child exists in parent

2019-06-22 19:04发布

问题:

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/

回答1:

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


回答2:

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>



回答3:

only one child in parent:

p:has(br:first-child:last-child)

bonus

p:has(br:only-child)


回答4:

Definitely yes, you can do it by chaining two different selectors:

  • Is the first direct child.
  • 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.