I’m trying to transfer the following mockup into working dynamic code but I’m having a few problems right now.
Mockup: http://www.imagebanana.com/view/a6yuqvgm/chat.png
The goal here is to implement the “negative margin” each message box has so that the messages overlap a bit. So, if person A (me) and person B have a conversation, all messages from person B should be on the right side and all of my messages (person A) should be on the left side. This part is obviously rather easy.
Also, if I answer to a message from my chat partner, my message should have a negative margin so that my message sort of “goes into” the message from my partner but on the other side. This is for design and space-saving reasons. The longer the messages, the greater the margin should be. Shorter messages need to have a smaller margin.
I’m currently a pit puzzled as how to successfully implement such things. A simple negative margin is not enough, because when a user sends two messages in a row, the messages overlap (the second one goes into the first one). The mockup shows the perfect situation, rotary messages (person A, person B, person A, person B, and so on), but that’s not always the case obviously.
My question now is, is that even possible with pure CSS? I guess I need to add some dynamic part, either in PHP or JS, both is fine. I just need some hints in the right direction.
You can do it in pure CSS if you don’t need need the margins sized according to the height of each message. The key in either case is the use of the adjacent (+) selector to target from-messages which follow to-messages and vice versa, avoiding overlap between consecutive messages from the same person.
Here’s how: http://jsbin.com/ujonoj/14/edit
Note the commented-out bit of CSS: you can use that to have static negative margin (however much you want) and avoid the JS, if need be.
Edit – added two safety checks to cover cases of very long messages following very short ones, and to stop setMargin running on consecutive to-to/from-from messages. The long-short safety check simply doesn’t set the negative margin greater than some percent (80 in my example) of the previous message.