Define the first `li` having a specific class inside` ul` only css

Is it possible to configure the first li target class inside ul ? eg:

  <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 opportunity?

+5
source share
4 answers

Use :first-child pseudo :first-child class and 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> 
+6
source

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

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

and

 ul li:nth-child(4) { //some css } 
+2
source

You cannot select with class as a parameter for first-child . Instead, use the ~ operator to select the opposite. Use rest styles except for the 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> 
+2
source

Typically, you can only orient an element, the value of a named attribute in it, or the name of an attribute in an element. So, I would say the answer may be ... no? (limited by my own knowledge)

It is said ..

Is it possible to insert an empty <li> before each element that you want to target?

If so, you can easily select the following items:

 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> 
0
source

Source: https://habr.com/ru/post/1262159/


All Articles