Solution 1 :

Use a child combinator (>) to apply the rule to a direct child * (universal selector) that is a :last-child.

Note: the universal selector (*) can be omitted, but I find it easier to read.

.container > *:last-child {
   margin-bottom: 0px;
   border: 1px solid red;
}
<div class="container">
   <p>...</p>
   <div>...</div>
   <ol>...</ol>
   <p>...p</p>
</div>

Solution 2 :

.container > :last-child {
    margin-bottom: 0px;
    color: red;
}
<div class="container">
        <p>...</p>
        <div>...</div>
        <ol>...</ol>
        <p>...p</p>
</div>

Solution 3 :

In this i have used the child combinator >

.container {
  margin-bottom: 20px;
  border: 1px solid red;
}

.container > :last-child {
  background: Red;
}
<div class="container">
  <p>...</p>
  <div>...</div>
  <ol>
    <li>...
      <li>
  </ol>
  <p>...p</p>
</div>

<div class="container">
  <p>...</p>
  <div>...</div>
  <ol>
    <li>...
      <li>
  </ol>
  <p>...p</p>
  <ol>
    <li>...
    </li>
  </ol>
</div>

<div class="container">
  <p>...</p>
  <div>...</div>
  <ol>
    <li>...
    </li>
  </ol>
  <p>...p</p>
  <div>...</div>
</div>

Problem :

Let’s say that I have the following html:

<div class="container">
   <p>...</p>
   <div>...</div>
   <ol>...</ol>
   <p>...p</p>
</div>

I would like to apply style to the last element inside the container class. In the example above I would like to apply margin-bottom to the last <p>. Keep in mind that the last element is not always <p>, it could be anything.

I tried with

.container:last-child {
   margin-bottom: 0px;
}

but the style wasn’t applied. Could someone point me in the right direction please?

Comments

Comment posted by Tyler Roper

.container:last-child

Comment posted by Temani Afif

simply add a space

Comment posted by Tyler Roper

@TemaniAfif That’s closer but would still select all “last children”, not just the last child of the container itself.

Comment posted by Temani Afif

@TylerRoper yes but this is the main issue of his question. He’s applying the wrong selector by omitting the space. Fixing this will give the needed result then we may have the other side effect of selecting all the childs. In this case we can add another duplicate related to

Comment posted by Tyler Roper

@TemaniAfif Agreed on all accounts. I think your suggestion certainly pushed OP closer to what they wanted, just noting that it still may present them with a hiccup or two.

By

Leave a Reply

Your email address will not be published. Required fields are marked *