0

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?

Alan M
  • 616
  • 5
  • 15
Alex
  • 65
  • 7
  • 1
    `.container:last-child` doesn't mean *"last child of `.container`"*, but rather *"any `.container` that is also a last child."*. You may want `.container > *:last-child` instead. – Tyler Roper Jan 17 '20 at 18:56
  • simply add a space `.container :last-child` – Temani Afif Jan 17 '20 at 19:06
  • @TemaniAfif That's closer but would still select all "last children", not just the last child of the container itself. – Tyler Roper Jan 17 '20 at 19:58
  • @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 `>` – Temani Afif Jan 17 '20 at 20:53
  • @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. – Tyler Roper Jan 17 '20 at 20:54

3 Answers3

2

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

.container > :last-child {
    margin-bottom: 0px;
    color: red;
}
<div class="container">
        <p>...</p>
        <div>...</div>
        <ol>...</ol>
        <p>...p</p>
</div>
Wang Liang
  • 4,244
  • 6
  • 22
  • 45
0

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>
Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39