Home > database >  How to place an item conditionally to right or left of a container?
How to place an item conditionally to right or left of a container?

Time:12-13

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?

CodePudding user response:

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  >
  <div >Owner message...</div>
  <div >Response message...</div>
</div>

You can implement Message component like this:

<div classname=`message ${isOwnMessage ? 'right' : 'left'}`>{text}</div>

CodePudding user response:

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 >
  <div >hi</div>
  <div >hello</div>
  <div >what's up</div>
  <div >i'm weekending</div>
  <div >hbu</div>
</div>

CodePudding user response:

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>
  • Related