0

How to select all last messages after each "Hello" in css?

Not using JavaScript.

.my {
  text-align: right;
}

.my:last-of-type {
  color: red;
}
<p class="me">Hello</p>

<p class="my">message</p>
<p class="my">message</p>
<p class="my">message</p>
<p class="my">last message</p>

<p class="me">Hello</p>
<p class="me">Hello</p>

<p class="my">message</p>
<p class="my">message</p>
<p class="my">last message</p>

It should be: image

2 Answers2

3

I think I have a solution for you, you need to reverse your messages then css magic can happen:

.chat-messages {
  display: flex;
  flex-direction: column-reverse;
}

.my {
  text-align: right;
}

.my:first-of-type, .me + .my {
  color: red;
}
<div class="chat-messages">
  <p class="my">last message</p>
  <p class="my">message</p>
  <p class="my">message</p>
  <p class="me">Hello</p>
  <p class="me">Hello</p>
  <p class="my">last message</p>
  <p class="my">message</p>
  <p class="my">message</p>
  <p class="my">message</p>
  <p class="me">Hello</p>
</div>
VXp
  • 11,598
  • 6
  • 31
  • 46
Rahul
  • 4,294
  • 1
  • 10
  • 12
  • It's worth to note that new messages have to be inserted e.g. as `chatMsgs.insertAdjacentHTML('afterbegin', '

    ...

    ');` and not at the _bottom_ of the _parent element_.
    – VXp Dec 15 '18 at 12:26
0

You either need to wrap each group of .my messages in a container to make use of :last-of-type or apply a specific modifier class to the last message:

.my {
  text-align: right;
}

.my.last {
  color: red;
}
<p class="me">Hello</p>

<p class="my">message</p>
<p class="my">message</p>
<p class="my">message</p>
<p class="my last">last message</p>

<p class="me">Hello</p>
<p class="me">Hello</p>

<p class="my">message</p>
<p class="my">message</p>
<p class="my last">last message</p>
Zealot
  • 687
  • 4
  • 17