首页 > 解决方案 > 如何对齐div标签左右极端?

问题描述

我已经使用 socket.io 创建了聊天应用程序,但是来自发送者和接收者的消息必须在极右和极左。我怎样才能做到这一点 ?我已经添加了样式,但消息不是一个在另一个之下,而是内联。我该如何解决?

代码:

<div id="messages" className="card-block">
                            {this.state.messages.map((message, index) => {

                                let word = message.message.split('#')

                                if(word[0] === this.props.match.params.user){
                                    return (
                                        <div key={index} className="msgBoxRight"><p className="msgTextRight">{word[1]}</p></div>
                                    )
                                }else{
                                    return (
                                        <div key={index} className="msgBoxLeft"><p className="msgTextLeft">{word[1]}</p></div>
                                    ) 
                                }

                            })}
                        </div>

CSS:

#messages{
    height:300px;
    overflow: scroll;
    width: 100%;
}

.msgBoxRight {
    max-width: 350px;
    margin-top: 50px;
    float: right;
}

.msgTextRight {
    padding: 10px;
    background-color: #EBEEFD;
    border-radius: 25px;
}

.msgBoxLeft {
    max-width: 350px;
    margin-top: 10px;
    float: left;
}

.msgTextLeft {
    padding: 10px;
    background-color: #EBEEFD;
    border-radius: 25px;
}

截屏: 在此处输入图像描述

它应该如何显示:

在此处输入图像描述

标签: htmlcss

解决方案


您可以使用弹性盒。而且我认为您不需要div包装纸。

#messages {
  height: 300px;
  overflow: scroll;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.msgTextRight,
.msgTextLeft {
  max-width: 350px;
  background-color: #EBEEFD;
  border-radius: 25px;
  padding: 10px;
}

.msgTextRight {
  margin-top: 50px;
  margin-left: auto;
}

.msgTextLeft {
  margin-top: 10px;
  margin-right: auto;
}
<div id="messages" class="card-block">
   <p class="msgTextRight">hello Aditya</p>
   <p class="msgTextLeft">hello world</p>
   <p class="msgTextRight">i am varun</p>
   <p class="msgTextLeft">i am Aditya</p>
</div>


推荐阅读