how to select the first element of each class with css


The code is already written, without each class having a parent. 🙁 -So now the whole page is a bunch of sections. classes may have any number of sections with any number of articles inside each section. they determined that each class was a category, which is why some classes have many sections. I need a left and top border only, for each class/category. so that all sections in each category are grouped together with different colors. So other than me writing more html and giving each category its own div parent, I am trying to use CSS selectors to grab the first section of every class.

jsfiddle with code started, but have a lot more to code yet.

<section class="a">
  <article>class a article one section one</article>
  <article>class a article two section one</article>
<section class="a">
  <article>class a article one of section 2</article>
<section class="b">...

I want a border-top above each section that starts a new class. so class “a” first section only will have a red top border, class b first section will have a blue border, and so on.
I added a class called top and inserted it in the sections I needed, but was there a better way than this?

css starts here
.a{border-left:solid red;}{border-top:solid red;}
.b{border-left:solid green;}{border-top:solid green;}
.c ...
....all the way to class z+

I tried using css4 – but browsers not using it yet.

:nth-match(1 of section.a{border-top:solid red;}

I have a lot of sections not started yet, which is why I am hoping there is a faster way. Jquery is not ruled out, haven’t thought about that yet.


No it’s not possible because all CSS selectors selects element of type.

and unfortunately there is no selector like first-of-class or something like that. link for all css selectors :

You can use [attribute=value] but it’s only purpose is to check weather first section has that attribute with provided value or not.

You have to use javascript or whatever other language you are working with to select the way you want(by first class of type)

Answered By – Nirpendra Patel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published