skip to Main Content

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


  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.

    Login or Signup to reply.
  2. :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>
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search