2

I would like to know how to select first-child in actual scope, let me give you an example so you could understand my question correctly:

HTML:

<div class="comment commentCompany">
  <div class="commentTop"></div>
  <div class="commentMiddle">
    Text of comment level two comment.
    <div class="comment">
      <div class="commentTop"></div>
      <div class="commentMiddle">
        Text of comment level three.
        </div>
      <div class="commentBottom"></div> 
    </div>
    </div>
  <div class="commentBottom"></div> 
</div>

CSS that first came to my mind to affect classes commentTop, commentMiddle, commentBottom inside the commentCompany class but only in a direct scope was this:

.commentCompany .commentTop:first-child{/*affect company's .commentTop*/}
.commentCompany .commentMiddle:first-child{/*affect company's .commentMiddle*/}
.commentCompany .commentBottom:first-child{/*affect company's .commentBottom*/}

But there are two problems: :first-child is more like first class's element's type(not really a first-child of class) (would have to use nth-child), and the main problem : it affects also the nested comment - which is not company's comment - so how to get only the direct scope of commentCompany?

I would like to know CSS2 && CSS3 solution if there is any difference. Thanks! :)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
jave.web
  • 13,880
  • 12
  • 91
  • 125

1 Answers1

5

You want the child combinator >, not the :first-child or :nth-child() pseudo-classes:

.commentCompany > .commentTop
.commentCompany > .commentMiddle
.commentCompany > .commentBottom

This only selects .commentTop, .commentMiddle and .commentBottom that are directly nested within .commentCompany (within your so-called "actual scope"). See this answer for an illustration.

Using the space, the descendant combinator, means you're trying to get every first child of its parent that is nested within .commentCompany. Combine that with your class selectors and you get all kinds of unexpected results.

The child combinator is part of CSS2; there is no CSS3-only solution.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • not to mention the :first-child and :nth-child() act very differently between CSS2 and CSS3 – Charles380 Aug 07 '13 at 18:07
  • 1
    @Charles380: `:first-child` is identical to `:nth-child(1)`. – BoltClock Aug 07 '13 at 18:09
  • @BoltClock sorry with CSS2 there wasn't an :nth-child() that's what I was getting at – Charles380 Aug 07 '13 at 18:11
  • 1
    @BoltClock I've edited the answer and added "Here is a JSFiddle show-up: http://jsfiddle.net/36N6t/ (notice the color behaviour - if you dont set it anywhere before the red will be used (nested will inherit))" - just for the case you wont accept the edit :) – jave.web Aug 07 '13 at 18:50