1

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>
  • 1
    You can try `.someText:last-of-type` [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type). Though I'm a bit confused what you're trying to achieve because those `someText` elements are almost certainly going to be wrapped in some parent element like ``, even if you don't explicitly do it – Dennis Kats Aug 08 '23 at 05:05
  • If one of the elements is somehow special and you need to style it differently add a class to it that you can target. – Martin Aug 08 '23 at 06:16

3 Answers3

1

: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>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

you can do two ways i am here attaching my pen look into it.

.someText:last-of-type p {

    enter code here.     

}

https://codepen.io/fbarun/pen/LYXvBpo

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
Arun
  • 17
  • 5
-1

The pseudo class that you're looking for is :last-of-type

.someText:last-of-type {
    color: blue;
}

This will make the last someText element blue.