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>
</div>

How can I do it?

 


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






1 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.

1
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





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

Full Name *

Email *




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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly