Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target first `li` having specific class inside `ul` with css only

Tags:

html

css

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?

like image 215
richa_pandey Avatar asked Jan 02 '17 06:01

richa_pandey


People also ask

How do you target first class in CSS?

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

How do I get the first span in CSS?

The CSS selector div:first-of-type only selects the very first element of its type and styles it. The div span:first-of-type selects the first span in each div since the div is the parent element.

How do I select a class child in CSS?

The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.


2 Answers

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>
like image 193
Ricky Avatar answered Sep 27 '22 18:09

Ricky


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

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

and

ul li:nth-child(4) {
 //some css
}
like image 24
Lubos Voska Avatar answered Sep 27 '22 19:09

Lubos Voska