Reputation: 1487
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.
Upvotes: 26
Views: 37299
Reputation: 810
If I can understand correctly the question the goal here is to hide every child (h3
and div.classa
) with the exception of the first h3
and the div.classa
next to it.
The easiest way to accomplish it is a combination of the :first-of-type
and the ~
(general siblings) selectors.
div.classa:first-of-type ~ * { 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>
Upvotes: 2
Reputation: 2879
Check out here https://jsfiddle.net/32vw04jg/1/
<div class="content">
<div>
<h3>abc</h3>
<div class="classa">some content</div>
</div>
<div>
<h3>xyz</h3>
<div class="classa">more content</div>
</div>
<div>
<h3>header3</h3>
<div class="classa">another content</div>
</div>
</div>
.content > div:not(:first-child) {
display: none;
}
Upvotes: 50
Reputation: 1
.content > *{ display: none;}
.content > *:first-child{ display: block !important; }
Upvotes: -2
Reputation: 2115
You can do it like that:
<div class="content">
<h3>abc</h3>
<div class="classa">some content1</div>
<h3>xyz</h3>
<div class="classa">more content2</div>
<h3>header3</h3>
<div class="classa">another content3</div>
</div>
Css:
.content > .classa:not(:nth-of-type(2)) {
display:none;
}
Upvotes: 4
Reputation: 2480
There is new CSS3's :first-of-type
for your case:
Demo
.content h3, .content div{
display:none;
}
.content .classa:first-of-type{
display : block;
}
Upvotes: 2
Reputation: 193261
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>
Upvotes: 16
Reputation: 18113
The problem in your code is that you want to hide the first .classa
, but the first .classa
isn't the first child in .content
, the h3
is the first child.
So as an alternative to the :not()
pseudo class, you could use nth-of-type(n+2)
. It will select all elements with the same type, except the first one.
div.classa:nth-of-type(n+2) {
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>
Upvotes: 14
Reputation: 705
You can try the :not
pseudo class — https://developer.mozilla.org/en-US/docs/Web/CSS/:not
See this answer
Upvotes: 1