Oto Shavadze
Oto Shavadze

Reputation: 42773

css "first-child" with li tag

   <ul>
        <li class="bla">aaa</li>
        <li class="my_li">sss</li>
        <li class="my_li">ddd</li>
        <li class="my_li">fff</li>
    </ul>

css:

    .my_li:first-child{
            color: #090;
    }

this not working, if make for first li tag class not "bla", but "my_li", alreday li element set green color. Someone tell please, why this happened.

Upvotes: 1

Views: 1275

Answers (6)

w3jimmy
w3jimmy

Reputation: 712

I think the best solution is to add a second class to your li element

CSS:

.first_li{ color:#090; }

<ul>
  <li class="bla">aaa</li>
  <li class="my_li first_li">sss</li>
  <li class="my_li">ddd</li>
  <li class="my_li">fff</li>
</ul>

you could solve your problem with the :nth-child(n) selector, but that means you need to know exactly in which order is the li element inside its parent ul (in this case 2nd child) and if you insert more elements this will fail.

css: .my_li:nth-child(2){ color: #090;}

Upvotes: 1

jackJoe
jackJoe

Reputation: 11148

As Quentin said, :first-child referes to the first element of its parent.

If you want to target the first element of your example list, do this:

ul li:first-child {
   color: #090;
}

Upvotes: 1

ygssoni
ygssoni

Reputation: 7349

If you dont want to change the class for the first element, use :

ul li:first-child{
            color: #090;
    }

Upvotes: 1

Simon
Simon

Reputation: 5493

You should use this selector:

.my_li:nth-child(2) { ... }

(if I'm understanding your question currently and you want the 2nd <li> to have this style)

Upvotes: 2

fd8s0
fd8s0

Reputation: 1927

It doesn't work because that selector means you're choosing an element with class my_li which is the first child of its parent, that is not present in your html.

Try

<ul>
    <li class="my_li">aaa</li>
    <li class="my_li">sss</li>
    <li class="my_li">ddd</li>
    <li class="my_li">fff</li>
</ul>

Then your rule will apply to aaa.

http://www.w3schools.com/cssref/sel_firstchild.asp

Upvotes: 1

Quentin
Quentin

Reputation: 943615

The first element that is a member of the class "my_li" is the second child of its parent.

:first-child selects elements that are the first child of their parent.

Upvotes: 6

Related Questions