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.
...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>
You can use the general sibling combinator in this case.
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With