0

I am trying to select the second span from the li element

html

<ul>
    <li>
       <span class="item1-class">item 1</span>
       <span class="item2-class">item 2</span>
    </li>
    <li>
       //Can i select this item only without 
       //adding additional class or id
       <span class="item1-class">item 1 needs to be selected</span>              
       <span class="item2-class">item 2</span>
    </li>
    <li>
       <span class="item1-class">item 1</span>
       <span class="item2-class">item 2</span>
    </li>
    <li>
       <span class="item1-class">item 1</span>
       <span class="item2-class">item 2</span>
    </li>
</ul>

my sass css

li {
    .item1-class {
        color:red;
    }
}

I can't change the html so I can only use css to select the second item1-class. Is there anyway to do this?

1
  • 1
    Not sure what you mean; the obvious answer is to just use .item2-class {}, so I'm assuming you mean something else.
    – TylerH
    Apr 2, 2015 at 18:38

3 Answers 3

4

You can achieve this using the :nth-child/:nth-of-type pseudo selector.

edit apparently browser support is now pretty solid, minus IE8. http://caniuse.com/#feat=css-sel3

edit 2 apparently there is an issue with nth-child on iOS 8 ( iOS8 Safari after a pushState the :nth-child() selectors not works ), so nth-of-type is the more stable option.

 li:nth-of-type(2) .item1-class{
      //your styling here
 }
1

I think you are probably looking for something like :nth-of-type().

CSS:

li:nth-of-type(2) .item1-class {
    color:red;
}

JSFiddle

0

For the record, I like @Jesse Kernaghan's answer. Using the nth-child selector is what you are looking for.

SCSS

ul {
    li {
        span {
            &:nth-child(2) {
                color: red;
            } 
        }
    }
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.