Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling CSS consecutively

Tags:

html

css

I have the following scenario:

This HTML is dynamically generated and continually growing.

<div id="messages">
    <div class="message person-1">
    <div class="message person-1">
    <div class="message person-2">
    <div class="message person-2">
    <div class="message person-2">
    <div class="message person-1">
    ...
</div>

Applying normal styling I get this:

Chat styling

However, I wish to group consecutive messages by the same person. This would mean, for each consecutive group, removing the margin between consecutive classes when they're not the first or last-child and also altering the first and last child's border radii.

I have looked into this: http://www.sitepoint.com/contiguous-sibling-selector/ but not sure how to get that to work for a list of indeterminate length.

Is this possible at all?

like image 278
iamyojimbo Avatar asked Feb 21 '26 06:02

iamyojimbo


1 Answers

Without changing the HTML, we can use the + selector to select continuous messages from the same person. We can then overlap the border-radius to hide it:

.person-1 + .person-1,
.person-2 + .person-2 {
  margin: -10px 5px 0;
}

messages example

Complete Example

#messages {
  width: 200px;
}
.message {
  padding: 10px;
  color: #FFF;
  margin: 5px 5px 0;
  width: 100px;
  border-radius: 5px;
}
.person-1 {
  background: green;
  float: left;
  clear: both;
}
.person-2 {
  background: purple;
  float: right;
  clear: both;
}
.person-1 + .person-1,
.person-2 + .person-2 {
  margin: -10px 5px 0;
}
img {
  padding-top: 10px;
}
<div id="messages">
  <div class="message person-1">Hello How are you?</div>
  <div class="message person-2">Good thanks</div>
  <div class="message person-2">and you?</div>
  <div class="message person-2">:)</div>
  <div class="message person-1">I'm so great!</div>
  <div class="message person-2">Awesome</div>
  <div class="message person-1">Yeah!</div>
  <div class="message person-2">Plz Respond</div>
  <div class="message person-2">Plz Respond</div>
  <div class="message person-2">Plz Respond
    <img src="http://www.placehold.it/100x100">
  </div>
  <div class="message person-2">Plz Respond</div>
  <div class="message person-1">Yeah!</div>
  <div class="message person-1">hi!</div>
  <div class="message person-1">hi!</div>
</div>
like image 137
misterManSam Avatar answered Feb 22 '26 21:02

misterManSam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!