How to apply a CSS to first element of class only?

I have a question, I would like to know, how can I apply a CSS to only first-child of a class, I am aware of :first-child CSS selector, but I am not able to use it.

I want to apply border-top to all the div with class "b" except the first one, here is sample HTML

<div class="a">
   <div class="b"></div>
   <div class="b"></div>
    <div class="b"></div>

How can I do it?


Asked by:- Sam
: 4395 At:- 6/6/2018 9:50:08 AM
CSS css first of class css select first element

3 Answers
profileImage Answered by:- jon

Yes, as you have heard of :first-child, we can use it and apply a different CSS style to first one, so as for your requirement, CSS code should be

 .a > .b {
     border-top: 5px solid black

.a > .b:first-child {
    border-top: none

In the above CSS code, we are first giving border-top to all the child element of "a" class which has "b" class, in the second line of the code we are removing border-top from the only first-child element of "a" class which has "b" class.

The :first-child selector allows you to target the first element immediately inside another element, it is used to style content based on its relationship with parent and sibling content.

At:- 6/6/2018 10:18:30 AM
got it, thanks for explanation and providing solution 0
By : Sam - at :- 6/6/2018 12:51:39 PM

profileImage Answered by:- pika

you can also use first-of-type or nth-of-type(1) CSS propertu to apply on first element of class

  color: green;  

.changeColor:first-of-type {
  color: red;  


<div class="home">
  <p class="changeColor">first</p>
  <p class="changeColor">second</p>
  <p class="changeColor">third</p>
  <p class="changeColor">fourth</p>

Here is fiddle


At:- 3/6/2022 6:02:10 PM

profileImage Answered by:- vikas_jk

You can also use the :nth-of-type selector, to apply CSS to first element only. Example

    border:5px solid red;

Should apply red-border of 5px to first element only, since we mentioned :nth-of-type(1), if we had to apply CSS on third element, then CSS would be :nth-of-type(3)

<div class="a">
   <div class="b">Test</div>
   <div class="b">Test</div>
    <div class="b">Test</div>

Fiddle link:


At:- 7/20/2022 2:38:48 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use