Reputation: 1305
I am implementing a chat for my web app and I find difficulty in placing the messages correctly and I am not skilled in CSS. I want to place the owner's messages to right and the other user's on the left.
Here some sample code:
// this is the container
<div className="container">
{messages.map(({ text='', isOwnMessage=false })=> <Message text={text} isOwnMessage={isOwnMessage}/>)}
</div>
// This is the message component
//...
<div classname="message">{text}</div>
I need to place <Message />
component to left if isOwnMessage is false, on the right otherwise. I know It can be done by giving position absolute and right:0
but that's not good for me. I tried as well: marginLeft: '50%'
but then there's a problem with the dimension of the message itself, which is max 80% of the container, otherwise is like its content.
So how would you do that?
Upvotes: 1
Views: 693
Reputation: 149
Made these changes using flex.
.flex{
display:flex;
}
.flex-col{
flex-direction:column;
}
.ml-auto{
margin-left:auto;
}
// Component
<div className="container flex flex-col">
{messages.map(({ text='', isOwnMessage=false })=> <Message text={text} isOwnMessage={isOwnMessage}
className={isOwnMessage?"ml-auto":""}
/>)}
</div>
// This is the message component
<div classname={["message", props.className].join(" ")}>{text}</div>
Upvotes: 1
Reputation: 33931
By using the align-self
property for flex children.
body {
font-family: sans-serif;
}
.conversation {
border: 1px solid black;
display: flex;
flex-direction: column;
gap: 0.2rem;
max-width: 300px;
padding: 0.5rem;
}
.message {
border-radius: 100vh;
padding: 0.5em 0.8em;
}
.self {
align-self: end;
background-color: #006aff;
color: white;
}
.other {
align-self: start;
background-color: gainsboro;
color: black;
}
<div class="conversation">
<div class="message other">hi</div>
<div class="message self">hello</div>
<div class="message other">what's up</div>
<div class="message self">i'm weekending</div>
<div class="message self">hbu</div>
</div>
Upvotes: 1
Reputation: 6584
I hope this help to solve your problem:
.message{
clear:both;
padding: 10px;
color: #eee;
}
.message.right{
background: green;
float:right;
}
.message.left{
background: cadetblue;
float:left;
}
<div class="container" >
<div class="message right">Owner message...</div>
<div class="message left">Response message...</div>
</div>
You can implement Message
component like this:
<div classname=`message ${isOwnMessage ? 'right' : 'left'}`>{text}</div>
Upvotes: 1