如何创建对话泡泡?

How to create speech bubble?

此对话框用于显示表单验证的错误消息

p.speech {
  position: relative;
  width: 200px;
  height: 40px;
  left: 100px;
  top: 100px;
  background-color: #FFFFFF;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  text-align: center;
  border: 1px solid red;
}
p.speech::before {
  content: ' ';
  position: absolute;
  width: 0;
  height: 0;
  left: -10px;
  top: -10px;
  border: 20px solid;
  border-color: #FF0000 transparent transparent transparent;
  -webkit-transform: rotate(25deg);
  -moz-transform: rotate(25deg);
  transform: rotate(25deg);
}
p.speech::after {
  content: ' ';
  position: absolute;
  width: 0;
  height: 0;
  left: -9px;
  top: -9px;
  border: 19px solid;
  border-color: #FFFFFF transparent transparent transparent;
  -webkit-transform: rotate(25deg);
  -moz-transform: rotate(25deg);
  transform: rotate(25deg);
}
<p class="speech">here is a text</p>

创建一个对话泡泡,如下所示,

但是伪元素有一些线条不透明

我的问题是,

  1. lefttop 伪元素的值显示负值。为什么伪元素不基于relative段落元素定位?以便 lefttop 被赋予正值?

  2. 为什么伪元素用after伪元素不透明?

您可以通过创建一个两侧带有边框的元素,然后倾斜该元素以创建箭头而不是直角来实现此目的。还要注意稍微宽一点(准确地说是 sqrt(2))的顶部边框,因为这个通过倾斜变得更薄了。绝对定位也进行了调整,使边框对齐。

另请注意,您应该将消息本身放在一个元素中,并确保它位于箭头前面。

注意买者:较粗的边框尺寸很明显,箭头的右角有一个过冲进入气泡。正如其他人指出的那样,使用一些 SVG 很容易实现这一点,不会有这个问题。

p.speech {
  position: relative;
  width: 200px;
  height: 40px;
  left: 100px;
  top: 100px;
  background-color: #FFFFFF;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  text-align: center;
  border: 1px solid red;
}

p.speech::after {
  content: ' ';
  position: absolute;
  width: 20px;
  height: 20px;
  left: 20px;
  top: -11px;
  background: white;
  border-left: 1px solid red;
  border-top: 1.4px solid red;
  -webkit-transform: skew(0, 45deg);
  -moz-transform: skew(0, 45deg);
  transform: skew(0, 45deg);
}

p.speech span {
  position: relative;
  z-index: 1;
}
<p class='speech'>
  <span>Some error text message which is not covered by ::after</span>
</p>

正如其他人所建议的那样,SVG 是处理这种形状的好方法。你甚至可以code it inline with a path element。这是一个如何做到这一点的例子:

p{
  position:relative;
  width:200px;
  height:40px;
  padding: 30px 20px 10px;
  text-align:center;
  z-index:1;
}
svg{
  position:absolute;
  top:0; left:0;
  width:100%;
  height:100%;
  z-index:-1;
}
<p class='speech'>
  <svg width="240" height="80" viewbox="-1 -1 242 82">
    <path d="M40 1 V20 H220 Q240 20 240 40 V60 Q240 80 220 80 H20 Q0 80 0 60 V40 Q0 20 20 20z" 
          fill="transparent" stroke="red" stroke-width="2" />
  </svg>
  Some error text message which is not covered by ::after
</p>