Reputation: 1724
I am trying to create a chat application. Inside the chat container, I will add both sent and received messages. It is clear that the messages will not be in a specific order.
I need to add some margin at the end of each repeated series of sent or received messages.
<div class="container">
<div class="sent_message"></div>
<div class="sent_message"></div>
<!-- NEED MARGIN -->
<div class="received_message"></div>
<div class="received_message"></div>
<div class="received_message"></div>
<!-- NEED MARGIN -->
<div class="sent_message"></div>
<!-- NEED MARGIN -->
<div class="received_message"></div>
<!-- NEED MARGIN -->
<div class="sent_message"></div>
<div class="sent_message"></div>
<!-- NEED MARGIN -->
</div>
Is there any CSS selector to select the last-child
of each of the series of classes, or should I change the structure of the HTML?
Upvotes: 6
Views: 227
Reputation: 19485
You could select each .received_message
follwed by a .sent_message
and vice-versa, instead, using the selector .received_message + .sent_message, .sent_message + .received_message
.
.received_message + .sent_message, .sent_message + .received_message{
margin-top: 20px;
}
.container div{
width: 120px;
height: 40px;
border: 1px dashed white;
}
.received_message{
background: rebeccapurple;
}
.sent_message{
background: orange;
}
<div class="container">
<div class="sent_message"></div>
<div class="sent_message"></div>
<!-- NEED MARGIN -->
<div class="received_message"></div>
<div class="received_message"></div>
<div class="received_message"></div>
<!-- NEED MARGIN -->
<div class="sent_message"></div>
<!-- NEED MARGIN -->
<div class="received_message"></div>
<!-- NEED MARGIN -->
<div class="sent_message"></div>
<div class="sent_message"></div>
<!-- NEED MARGIN -->
</div>
Upvotes: 12