CSS select 第一个按钮与第二个按钮相同 class

CSS select first button with same class of the second button

它看起来很简单。我要display:none;第一个button。我有两个相同的 parent class。出于某种原因,我无法弄清楚为什么我没有达到我想要的结果。

.main-content .cbToolBar:first-child button{
  display:none;
}
<div class="main-content">
  <span class="cbToolBar">
    <button class="cbButton"></button>
  </span>
  <span class="cbToolBar">
    <button class="cbButton"></button>
  </span>
</div>

我的选择有问题,但我不知道是什么。

谢谢。

...there are other tags before but at the same level as 'cbToolBar' span, but I thought it would select the first child called 'cbToolBar'.

CSS 的 :first-child pseudo-class 选择器首先选择 child,而不考虑 class ]. documentation on :first-child states:

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

有几种解决方法。我建议的是,如果您的 .cbToolBar 元素是 .main-content parent 中唯一的 span 元素,您可以改为使用 :first-of-type pseudo-class selector:

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

.main-content .cbToolBar:first-of-type button{
  display:none;
}
<div class="main-content">
  <p>Hello, world!</p>
  <span class="cbToolBar">
    <button class="cbButton">Button 1</button>
  </span>
  <span class="cbToolBar">
    <button class="cbButton">Button 2</button>
  </span>
</div>

或者,如果您知道要隐藏的元素的确切位置,则始终可以只使用 :nth-child(n)。在这个例子中,我们要隐藏的元素是第二个,所以我们使用 :nth-child(2):

.main-content .cbToolBar:nth-child(2) button{
  display:none;
}
<div class="main-content">
  <p>Hello, world!</p>
  <span class="cbToolBar">
    <button class="cbButton">Button 1</button>
  </span>
  <span class="cbToolBar">
    <button class="cbButton">Button 2</button>
  </span>
</div>

在这种情况下,您可以使用通用兄弟组合器。

  • 为具有特定class
  • 的所有元素设置规则
  • 使用组合器select关注兄弟姐妹并取消设置规则

.cbToolBar button {
  display: none;
}
.cbToolBar ~ .cbToolBar button {
  display: inline-block;
}
<div class="main-content">
  <span>span</span>
  <span class="cbToolBar">
    <button class="cbButton">button</button>
  </span>
  <span>span</span>
  <span class="cbToolBar">
    <button class="cbButton">button</button>
  </span>
  <span>span</span>
</div>