如何使边框与其中的文字一样大

How to make border as big as text in it

所以看起来像这样:

这是消息的示例代码:

.allMsg {
  width: 100%;
}

.self {
  border-radius: 1rem;
  background-color: #28a745;
  text-align: right;
  padding-left: 5px;
  padding-right: 5px;
  margin-left: 5px;
  margin-right: 5px;
}

.friend {
  text-align: left;
}

#chatWith {
  text-align: center;
  font-family: sans-serif;
  font-size: 40px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
<div class='allMsg'>
  <p class='self chatMsg'>Hello</p>
</div>

我怎样才能使边框和里面的文字一样大...我以为填充会起作用但不幸的是它没有所以请帮助我。

您可以在容器上使用 flexbox:

.allMsg {
  width: 100%;
  display: flex;
  flex-flow: column nowrap;
  align-items: flex-end;
}

示例:

.allMsg {
  width: 100%;
  display: flex;
  flex-flow: column nowrap;
  align-items: flex-end;
}

.self {
  border-radius: 1rem;
  background-color: #28a745;
  text-align: right;
  padding-left: 5px;
  padding-right: 5px;
  margin-left: 5px;
  margin-right: 5px;
}

.friend {
  text-align: left;
}

#chatWith {
  text-align: center;
  font-family: sans-serif;
  font-size: 40px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
<div class='allMsg'>
  <p class='self chatMsg'>Hello</p>
  <p class='self chatMsg'>This is a test</p>
</div>

如果您将消息包装在另一个元素中,这是可能的。因此,假设所有消息都有一个全角元素,但是朋友的消息将向左对齐并具有蓝色背景,而您的消息将向右对齐并具有绿色背景。如果您不想过多更改标记,最简单的方法是将您的消息包装在一个范围内,而不需要更改 html.

中的任何其他内容

.allMsg {
  width: 100%;
}

.self span, .friend span {
  border-radius: 1rem;
  padding-left: 5px;
  padding-right: 5px;
  margin-left: 5px;
  margin-right: 5px;
}

.self span {
  background-color: #28a745;
}

.friend span {
  background-color: #2845a7;
}

.self {
  text-align: right;
}

.friend {
  text-align: left;
}
<div class='allMsg'>
  <p class='chatMsg friend'>
    <span>hello</span>
  </p>
  <p class='chatMsg self'>
    <span>hy</span>
  </p>
  <p class='chatMsg friend'>
    <span>how are you friend?</span>
  </p>
  <p class='chatMsg self'>
    <span>i'm fine thanks</span>
  </p>
</div>