5

Is it possible to target first li having specific class inside ul? for example :

 <ul>
     <li class="a"></li> <!-- I want to target this li -->
     <li class="a"></li>
     <li class="a"></li>
     <li class="b"></li> <!-- and this li -->
     <li class="b"></li>
     <li class="b"></li>
 </ul>

Any possibility?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Richa
  • 4,240
  • 5
  • 33
  • 50
  • 1
    what is your definition of `specific` class ? Because they are not unique. Also, are you looking to target any "change" in class names ? – karthikr Jan 02 '17 at 06:25
  • [Helpful](http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class) – Insane Skull Jan 02 '17 at 06:26
  • I would say add ids to the html but then again, I don't know if changing the html is even possible in your case. –  Jan 02 '17 at 06:39
  • @karthikr sorry if that specific word is misleading. I dont know the excat no of li's but i want to target first `a` and first `b` in `ul`. is it possible by css? – Richa Jan 02 '17 at 06:39
  • @ILoveCSS i cant add id as they are repeating themselves with ng-repeat – Richa Jan 02 '17 at 06:40

4 Answers4

6

Use the :first-child pseudo-class and the adjacent sibling selector +.

.a:first-child, /* Select the first child element */
.a + .b { /* Select the first element with 'b' class */
  background-color: dodgerblue;
}
<ul>
  <li class="a"></li>
  <li class="a"></li>
  <li class="a"></li>
  <li class="b"></li>
  <li class="b"></li>
  <li class="b"></li>
</ul>
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53
2

try selector :nth-child() and :first-child

ul li:first-child {  
//some css 
}

and

ul li:nth-child(4) {
 //some css
}
Lubos Voska
  • 177
  • 1
  • 10
2

You can't select with class as parameter for first-child. Instead use ~ operator to select the reverse. i.e apply styles for rest except first child.

li.a, li.b{
 color: green; /*your styles for first elemenets*/
}
li.a ~ .a { /*differentiate rest of them from first*/
  color: black;
}
li.b ~ .b {
  color: black;
}
<ul>
  <li class="a">1</li>
  <!-- I want to target this li -->
  <li class="a">2</li>
  <li class="a">3</li>
  <li class="b">4</li>
  <!-- and this li -->
  <li class="b">5</li>
  <li class="b">6</li>
</ul>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

Generally, you can only target an element, a value of a named attribute in it, or the name of an attribute in the element. So, I would say the answer might be...no? (limited to my own knowledge)

That being said..

Would it be possible to insert an empty <li> before each item you want to target?

If so, you can easily select those items like so:

ul li {
  color: red
}
li:empty {
  display: none
}
li:empty + li {
  color: green
}
<ul>
  <li></li>
  <li class="a">1</li>  <!-- I want to target this li -->
  <li class="a">2</li>
  <li class="a">3</li>
  <li></li>
  <li class="b">4</li>  <!-- I want to target this li -->
  <li class="b">5</li>
  <li class="b">6</li>
</ul>