Isaac Krementsov
Isaac Krementsov

Reputation: 706

How do I style a chat box in CSS?

I have a chat box that looks like this: enter image description here

My main issue is that all messages are a fixed width, when I want the width to auto-resize by the amount of text. The elements are all spans within the chat div, with a display of block (inline or inline-block will render side-by-side) and changed side margins to make messages 'stick' to one side. Here is my css

.psentMessage {
    text-align: right !important;
    background-color: #F0F0F0;
    margin-right: 0 !important;
    border-top-right-radius: 0 !important;
}
.pmessage {
    text-align: left !important;
    background-color: white;
    margin-left: 0 !important;
    border-top-left-radius: 0 !important;
}
.pmessage, .psentMessage {
    display: block !important;
    padding: 2vh 1vw;
    max-width: 85%;
    margin-top: 1vh;
    margin-bottom: 1vh;
    border-style: hidden;
    border-radius: 10px;
}

How can I make the divs auto-resize but still have them in this layout?

Upvotes: 1

Views: 3558

Answers (1)

haugsand
haugsand

Reputation: 420

This can be solved by a flexbox layout with flex-direction: column;.

When you add align-items: flex-start;, the width of each message is adapted to the content. Add align-self: flex-end; to the messages you want to align to the right side.

Simplified example: https://codepen.io/anon/pen/bMobqM

HTML:

<div>
    <p class="other">Hello</p>
    <p class="other">This is the project managment app</p>
    <p>gwkki</p>
    <p class="other">hello</p>
    <p class="other">hi</p>
    <p>Hello</p>
    <p class="other">online</p>
</div>

CSS:

div {
  background: #ccc;
  padding: 20px;
  width: 150px;
  display: flex;
  flex-direction:column;
  align-items: flex-start;
}
    
p {
  background: #fff;
  padding: 10px;
}
    
.other {
  align-self: flex-end;
  background: #ddd;
}

More information about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Upvotes: 2

Related Questions