ariel
ariel

Reputation: 3072

How can I hide all <h2>'s except the first one?

How can I hide all <h2>'s except the first one?

<div class="holder">
  <h2>SOme heading</h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
</div>

I am familiar that we can use something like:

p:nth-child(2)
{
  display:none;
}

But not sure how to hide all except the first one. Can someone point me in the right direction? Would like something that is cross-browser compatible.

Upvotes: 3

Views: 1176

Answers (6)

Josh Crozier
Josh Crozier

Reputation: 241118

Here is one option using the adjacent sibling selector

jsFiddle example

.holder h2 + h2 {
    display:none;
}

Probably your best option as + is supportted by IE7+

Selectors such as nth-child/:not only work in IE9+

Upvotes: 10

kave
kave

Reputation: 471

you could do this:

#parent h2{
    display: none;
}

#parent h2:first-child{
    display: block;
}

http://jsfiddle.net/mWn2R/

Upvotes: 2

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13546

Assuming there can be other tags between headings, with modern CSS we can write it as

h2:not(:first-of-type) { display: none; }

or

h2:nth-of-type(n+2) { display: none; }

To make the code compatible with IE8, we can use the following, similarly to JoshC's answer:

.holder h2 ~ h2 { display: none; }

But why is it necessary to have many invisible headings in the code? It seems to be not good for search engines...

Upvotes: 0

ddavison
ddavison

Reputation: 29042

See this fiddle

Here's an option using the :not pseudo-selector combined with the :first-child pseudo-selector.

div.holder h2:not(:first-child) {
  display: none;
}

Upvotes: 0

Ceres
Ceres

Reputation: 3668

h2:not(:first-child) {
    display: none;
}

Upvotes: 1

ashley
ashley

Reputation: 2767

h2:nth-child(n2) {
   display: none;
}

http://codepen.io/sacha/full/cAJEo

EDIT: This link can also be used to do any nth-child testing

Upvotes: 2

Related Questions