如何将div标签左右对齐?

时间:2018-10-30 07:43:30

标签: html css

我已经使用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;
}

截屏: enter image description here

应如何显示:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用Flexbox。 而且我认为您不需要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>

答案 1 :(得分:1)

在已浮动的元素中添加“ clear:both” (两个),即为'。msgBoxRight'' .msgBoxLeft'

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

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

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

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

.msgTextLeft {
  padding: 10px;
  background-color: #EBEEFD;
  border-radius: 25px;
}
<div id="messages" class="card-block">
  <div class="msgBoxRight">
    <p class="msgTextRight">hello Aditya</p>
  </div>
  <div class="msgBoxLeft">
    <p class="msgTextLeft">hello world</p>
  </div>
  <div class="msgBoxRight">
    <p class="msgTextRight">i am varun</p>
  </div>
   <div class="msgBoxLeft">
    <p class="msgTextLeft">i am Aditya</p>
  </div>
</div>