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?
Syntax. The nth-last-child pseudo-class is specified with a single argument, which represents the pattern for matching elements, counting from the end. :nth-last-child( <nth> [ of <complex-selector-list> ]? )
The examples of an+b are as follows: :nth-last-child(odd) /* represents all odd foo elements in their parent element, counting from the last one */ :nth-last-child(-n+2) /* represents the two last elements */
How to select an element that is the first or last child of its parent. The :first-child pseudo class means "if this element is the first child of its parent". :last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With