首页 > 解决方案 > 没有使用伪元素的带箭头的框

问题描述

我需要为工具提示制作一个带箭头的框,但我不能使用伪元素,因为:

  1. 盒子背景有点透明
  2. 它有边框

这是示例:

.box {
  margin: 60px 0 0 0;
  width: 250px;
  height: 50px;
  background-color: rgba(255, 144, 89, 0.5);
  border-radius: 5px;
  position: relative;
  border: 2px solid #ff6e26;
}

.box:after,
.box:before {
  bottom: 100%;
  left: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.box:after {
  border-color: rgba(136, 183, 213, 0);
  border-bottom-color: rgba(255, 144, 89, 0.5);
  border-width: 10px;
  margin-left: -10px;
}

.box:before {
  border-color: rgba(194, 225, 245, 0);
  border-bottom-color: #ff6e26;
  border-width: 12px;
  margin-left: -12px;
}
<div class="box"></div>

https://codepen.io/Masoudm/pen/qgvJGX

正如您所看到的,当我使背景透明时,它不适用于箭头,因为我已经在它后面使用了 ::before 作为它的边框。我想知道是否有另一种方法可以让我保持盒子大小动态。

更新:

盒子应该是这样的(除了顶部曲线)

在此处输入图像描述

标签: htmlcss

解决方案


基于这个先前的答案,我将稍微调整代码以具有透明背景。有两个主要技巧。伪元素的一半着色以避免与主元素相交并在主元素上使用渐变来创建边框顶部并为伪元素创建孔:

body {
 margin:0;
 background-image:linear-gradient(to right,yellow,pink);
}

.box {
  border: 2px solid red;
  border-top:transparent; /*make border-top transparent*/
  margin: 50px;
  height: 50px;
  position:relative;
  /* Use gradient to mimic the border top with a transparent gap */
  background:
    linear-gradient(red,red) left top /calc(50% - 10px*1.414) 2px,
    linear-gradient(red,red) right top/calc(50% - 10px*1.414) 2px,
    rgba(0,255,0,0.4);
  background-repeat:no-repeat;
}

.box:before {
  content: "";
  position: absolute;
  width: 20px;
  height: 20px;
  border-top: 2px solid red;
  border-left: 2px solid red;
  top: -11px;
  left: calc(50% - 11px);
  transform: rotate(45deg);
  background:linear-gradient(-45deg,transparent 50%,rgba(0,255,0,0.4) 50%);
}
<div class="box">

</div>


推荐阅读