biztiger biztiger - 7 days ago 6
CSS Question

Hide all except first child of an element using pure css

I am trying to hide every other child after first child of classa class element.



div.classa {
display:none;
}
div.classa:first-child {
display:block !important;
}

<div class="content">
<h3>abc</h3>
<div class="classa">some content</div>
<h3>xyz</h3>
<div class="classa">more content</div>
<h3>header3</h3>
<div class="classa">another content</div>
</div>





How to achieve this using pure css.

Answer

If you want to support IE8, then your only option is general sibling selector:

div.classa ~ .classa {
    display: none;
}
<div class="content">
    <h3>abc</h3>
    <div class="classa">some content</div>
    <h3>xyz</h3>
    <div class="classa">more content</div>
    <h3>header3</h3>
    <div class="classa">another content</div>
</div>

Comments