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?
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.
OR
You can also use the :nth-of-type selector:
.b:nth-of-type(1)
{
border:5px solid green;
}
Here is the sample fiddle: https://jsfiddle.net/qyhks1ea/
Answered by:- pika
you can also use first-of-type or nth-of-type(1) CSS propertu to apply on first element of class
.changeColor{
color: green;
}
.changeColor:first-of-type {
color: red;
}
HTML
<div class="home">
<p class="changeColor">first</p>
<p class="changeColor">second</p>
<p class="changeColor">third</p>
<p class="changeColor">fourth</p>
</div>
Here is fiddle https://jsfiddle.net/9Lk58gzb/
Thanks
Answered by:- vikas_jk
You can also use the :nth-of-type selector, to apply CSS to first element only. Example
.b:nth-of-type(1)
{
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>
</div>
Fiddle link: https://jsfiddle.net/d4bhxyk3/
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly