-1

:)

Why does my first paragraph not have a red background?

HTML:

    <div class="item">
        <h1><a href="http://localhost/test">Test</a></h1>
            <p>This is a new entry </p>
            <p>This is a new entry</p>
    </div>

CSS:

.item p:first-child {background:red}

Demo: http://jsfiddle.net/tv90yrbz/

Many thanks for any help with this.

Harry
  • 87,580
  • 25
  • 202
  • 214
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190
  • 3
    Because the `

    ` is not the first child :)

    – Harry Jul 15 '15 at 09:38
  • instead of using first-chid use .item p:nth-child(2) {background:red} – siva Jul 15 '15 at 09:43
  • @siva: Though it might work for the exact sample code provided in question, it won't always work because there could be cases where the `p` is not the 2nd child also. – Harry Jul 15 '15 at 09:45

1 Answers1

5

Because it's not the first child, the h1 is.

You can use first-of-type:

.item p:first-of-type {background:red}

http://jsfiddle.net/tv90yrbz/2/


Older browsers aren't supported though:

http://caniuse.com/#search=first-of-type

Curtis
  • 101,612
  • 66
  • 270
  • 352
  • Many thanks. Quick follow-up, how do I get it to just affect the first paragraph and not all the others on the page? demo> http://jsfiddle.net/tv90yrbz/3/ – michaelmcgurk Jul 15 '15 at 09:42
  • 1
    @michaelmcgurk: You would probably have to use some extra class on the parent container. Or, if the container is the first `div` in the page then you could do `div:first-of-type p:first-of-type`. – Harry Jul 15 '15 at 09:44
  • 1
    Absolutely brilliant, Harry - thanks so much to you & Curt :-D – michaelmcgurk Jul 15 '15 at 09:46