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>
: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.
.someText:not(:has(~ .someText))
.someText p {
color: green;
}
.someText:not(:has(~ .someText)) p {
color: blue
}
<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>
<p>Some irrelevant text</p>
</div>