Mark
Mark

Reputation: 3118

change color of first div within another div, with an h2 in between

I notice that in the following code:

<div id="test1">
    <div>1Lorem ipsum</div>
    <div>2Lorem ipsum</div>
</div>

With this css:

#test1 div:first-child{
    color:red;
}

The first div (1Lorem...) will be displayed red, but if I change the html to this:

<div id="test1">
    <h2>Header</h2>
    <div>Lorem ipsum</div>
    <div>Lorem ipsum</div>
</div>

The first div will no longer display red. Can anyone please advise me how to make that first div (1Lorem...) display in red while keeping the h2? I have to keep that h2 there, and I really need to use a method where this first-child div will be changed to red.

Upvotes: 1

Views: 316

Answers (2)

Paulie_D
Paulie_D

Reputation: 114991

#test1 div:first-child only selects a div that is also the first child

#test1 div:first-of-type will select the first div within 'test1.

Upvotes: 3

j08691
j08691

Reputation: 207861

You can use :first-of-type or :nth-of-type(1):

#test1 div:first-of-type{
    color:red;
}

jsFiddle example

Upvotes: 2

Related Questions