CSS 选择与第二个按钮具有相同类的第一个按钮

azh*_*hpo 5 html css css-selectors

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

.main-content .cbToolBar:first-child button{
  display:none;
}
Run Code Online (Sandbox Code Playgroud)
<div class="main-content">
  <span class="cbToolBar">
    <button class="cbButton"></button>
  </span>
  <span class="cbToolBar">
    <button class="cbButton"></button>
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)

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

谢谢。

Jam*_*lly 6

...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's :first-child pseudo-class selector selects specifically the first child, regardless of it's class. The 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.

There are several workarounds. The one I'd suggest is that if your .cbToolBar elements are the only span elements within your .main-content parent, you can instead use the :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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Or, if you know the exact position of your element you want to hide, you can always just use :nth-child(n). In this example, the element we want to hide is the second one, so we use :nth-child(2):

.main-content .cbToolBar:nth-child(2) button{
  display:none;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)