Search code examples
htmlcsscss-selectorspseudo-class

selecting first article inside of a section


I have this html:

<section id=mainContent">

    <h2>Lorremis</h2>

    <article class="one"></article>
    <article class="two"></article>
    <article class="three"></article>
    <article class="four"></article>
    <article class="five"></article>
    <article class="six"></article>
    <article class="seven"></article>
    <article class="eight"></article>
    <article class="nine"></article>

</section>

Each article has an image and a couple of paragraphs inside them.

If i apply the following css code:

section#mainContent article:nth-child(2) {

    display: none;

}

I expect the second article to display none. This does not happen though. The first article dissapears instead of the second. Now, if i remove the h2 tag, the first article dissapears as it should.

Why is this?


Solution

  • As the others have said, nth-child selects child independent of tag type. You can use the nth-of-type selector instead

    #mainContent article:nth-of-type(2) { display none; }