I am wondering if there’s another way using CSS to style the last child element without the use of the :last-child
pseudo class? For example, here is my HTML code:
<div>
<div class="someText">
<p>Some text about Biology</p>
</div>
<div class="someText">
<p>Some text about Math</p>
</div>
<div class="someText">
<p>Some text about Environmental Science</p>
</div>
<div class="someText">
<p>Some text about physics</p>
</div>
</div>
Let’s say I want to change the text color on the last someText element to blue. This is my CSS:
.someText p{
color: green;
}
.someText:last-child p{
color: blue
}
While this works, I am wondering if there is a way to style the last element without using pseudo class?
I am asking because I want to remove the <div>
from my HTML that is wrapping the someText
classes.
Basically how would I apply the CSS to the last child if the my HTML instead looked like this:
<div class="someText">
<p>Some text about Biology</p>
</div>
<div class="someText">
<p>Some text about Math</p>
</div>
<div class="someText">
<p>Some text about Environmental Science</p>
</div>
<div class="someText">
<p>Some text about physics</p>
</div>
3
Answers
The pseudo class that you’re looking for is
:last-of-type
This will make the last
someText
element blue.:last-of-type
may not be suitable here since that means you cannot have another<div>
after your HTML code in the same level, even with a different class name.You may consider combining
:not()
and:has()
pseudo class to mimic:last-of-class
. But pay attention that:has()
hasn’t been widely supported yet.you can do two ways i am here attaching my pen look into it.
https://codepen.io/fbarun/pen/LYXvBpo