当父母中只有一个孩子时的选择器 [英] Selector for when only one child exists in parent

查看:72
本文介绍了当父母中只有一个孩子时的选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CSS选择器,我想知道我是否可以构建一个自定义的CSS选择器,使其仅在类.widget-button(示例代码)中只有一个才能工作?

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>

因此,您会假设此工作具有伪选择器(:only-child ?)的组合,该组合可用于上述工作?但是下面的例子不应该应用任何选择/样式,因为那里有一个以上的选择/样式.

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>

这里是JSFiddle https://jsfiddle.net/2L593m3x/

Here a JSFiddle https://jsfiddle.net/2L593m3x/

推荐答案

如果您可以创建自定义标签(或 Web组件得到广泛支持),则可以使用:only-of-type:

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>

这篇关于当父母中只有一个孩子时的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆