Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS select first button with same class of the second button

It's as simple as it looks like. I want to display:none; the first button. I have two of them with same parent class. For some reason I can't figure out why I don't achieve the result I want.

.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 is something wrong with my selection but I can't figure out what.

Thanks.

like image 832
azhpo Avatar asked Jan 09 '15 13:01

azhpo


2 Answers

...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;
}
<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>

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;
}
<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>
like image 148
James Donnelly Avatar answered Oct 27 '22 10:10

James Donnelly


You can use the general sibling combinator in this case.

  • Set a rule for all elements with a certain class
  • Use the combinator to select following siblings and unset the rule

.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>
like image 21
Salman A Avatar answered Oct 27 '22 12:10

Salman A