Jrn
Jrn

Reputation: 1235

CSS - Only select the first set of classes

I'm trying to figure out how to only select the first set of a class and apply CSS to it.

In the code below I'm trying to apply a color on the first set of div's with the class .item

<div class="field-items">
  <div class="item">This text should be red</div>
  <div class="item">This text should be red</div>
    <div class="field-items">
      <div class="item">This text should NOT be red</div>
      <div class="item">This text should NOT be red</div>
      <div class="item">This text should NOT be red</div>
      <div class="item">This text should NOT be red</div>
    </div>
  <div class="item">This text should be red</div>
  <div class="item">This text should be red</div>
</div>

The problem is that the second set of .item div's is also getting the color: red; css. I've been playing around with selectors like :nth-child, :nth-of-type, >, +,... but I can't figure out how to do this.

The best I can come up right now is to override the css for the second set.

.item {
  color: #cc3333;    
}
.item .item {
  color: #000;
}

Any help is appreciated.

Upvotes: 0

Views: 160

Answers (2)

BoltClock
BoltClock

Reputation: 723438

You will need to find out what element is the parent of the top-level .field-items, then attach it to the selector along with > combinators. For example if your parent element is .parent:

.parent > .field-items > .item {
  color: #cc3333;
}

Using .field-items > .item alone is not enough since you also have .field-items nested within .field-items, both of which have .item children.

Upvotes: 5

phpguest
phpguest

Reputation: 804

Here is css without adding class

.field-items:first-child > .item{color:red;}

Upvotes: 0

Related Questions