문제

this is my code and I am going to select first child that is <span>

<div class="textTextmenu">
      <img src="pic/postimage.png"/>
        <span>
            I need to select this span
        </span>
        <span>
            span 2
       </span>
   </div>

I want to do this with first-child, but I don't know how to use first-child

Like this:

.textTextmenu span:first-child{
 /*
    writing code here
 */
  color:red;
}
도움이 되었습니까?

해결책 2

Here is all to make you understand

1)    .textTextmenu span:first-of-type { color:red } 
2)    .textTextmenu :nth-child(1){border:1px solid red;}
3)    .textTextmenu span:nth-child(2){color:red;}

DEMO 1

DEMO 2

DEMO 3

다른 팁

In your example, .textTextmenu span:first-child will not match anything. The first-child of .textTextmenu is an img.

You might actually want to look into first-of-type, or nth-child, e.g.

.textTextmenu span:first-of-type {}

or

.textTextmenu :nth-child(2) {}

Other approaches that would work in this particular example are + or :last-child, like so:

.textTextmenu span {
    /* Style the first span */
}
.textTextmenu span + span {
    /* Style the next span */
}

or

.textTextmenu span {
    /* Style the first span */
}
.textTextmenu span:last-child {
    /* Style the next span */
}

I'm kind of confused as to what you want but...

.textTextmenu img:first-child{
  border:2px solid red;
 /*How to select First child? / this way is wronge and image is not selected*/
}

right?

.textTextmenu img:first-child{
  border:2px solid red;
}

this will select first img tag inside the div

any reason why you cant use first-of-type?

.textTextmenu span:first-of-type {
  ...styles go here... 

}

NOTE: as with many CSS pseudo-selectors, first-of-type is just an alias for nth-of-type(1) just as first-child is an alias for nth-child(1)

Is this be good? It selects each span after image in textTextmenu

.textTextmenu    img + span {} 

To select the image, instead of:

.textTextmenu span:first-child{}

do

.textTextmenu img:first-child{}

Here is a fiddle of it in action: http://jsfiddle.net/763K9/

.textTextmenu img + span{
  border:2px solid red;
 /*How to select First child? / this way is wronge and image is not selected*/
}

See the demo http://jsfiddle.net/nUwDb/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top