Robin Cox
Robin Cox

Reputation: 1490

how to use first child in my code?

In this example http://jsfiddle.net/eFhRE/1/ I wan't to make the a tag with id shoshone red with help of :first-child. Must be only the a tag with id shoshone and only with the use of :first-child. The rest of the a tags must remain blue.

Here is the html code:

<ul>
  <li class="mosonkhani">
    <a id="shoshone" href="#">Potsmare</a>
    <ul>
      <li><a href="#">Lorem</a></li>
      <li><a href="#">Ipsum</a></li>
      <li><a href="#">Dolores</a></li>
      <li><a href="#">Quiddam</a></li>
    </ul>
  </li>
</ul>

This is the css code I have tried with:

a { color:#00f; }
.mosonkhani:first-child {
  color:#f00;
}

How to do this?

Upvotes: 0

Views: 88

Answers (7)

Jeff
Jeff

Reputation: 12173

You are using :first-child wrong.

.mosonkhani > a:first-child {
  color:#f00;
}

That should do what you want.

Your Fiddle, updated: http://jsfiddle.net/jeffijoe/eFhRE/2/

first-child will get you the first instance of whatever your selector targets. I personally feel first-child is a mis-leading name.

Upvotes: -1

Paulie_D
Paulie_D

Reputation: 115126

There is no reason to complicate this width first-child or nth-child

Your anchor tag has an ID...use it

CSS

#shoshone {
    color:red;
}

JSFiddle

Upvotes: 0

Iqaan Ullah
Iqaan Ullah

Reputation: 37

Pseudo class :first-child matches the first element in its prefix.

Your code will match the first ".mosonkhani" element in the document.

If you have to select the first 'a' (link) element in any .mosokhani, use:

.mosonkhani a:first-child
{
    color: #f00;
}

Upvotes: 0

Andr&#233; Senra
Andr&#233; Senra

Reputation: 1

.mosonkhani>a {
    color:#f00;
}

Yes. I know i am not using the first-child.

Upvotes: -1

apsuva
apsuva

Reputation: 459

you dont need first-child.

a { color:#00f; }

.mosonkhani > a {
  color:#f00;
}

http://jsfiddle.net/eFhRE/6/

Upvotes: 0

David H&#246;lkeskamp
David H&#246;lkeskamp

Reputation: 180

.mosonkhani > a:first-child {...}

.mosnokhani:first-child would give every element (with class="mosonkhani")thats the first child inside an element the red color property.

Well .mosonkhani > a {...} would work in this case too.

Upvotes: 0

James Montagne
James Montagne

Reputation: 78650

.mosonkhani > :first-child {
  color:#f00;
}

You want the first child within .mosonkhani. What you had was an element with class mosonkhani which is also the first child.

http://jsfiddle.net/eFhRE/3/

Upvotes: 3

Related Questions