CSS实现对话框样式

1,414 阅读1分钟

实现这种扁平化的气泡对话框只需用伪类做小三角即可

实现效果

image.png

代码

<div class="marker-label">
    <span>测试项目2</span>
</div>
.marker-label {
    position: relative; 
    height: 24px;
    padding: 0 8px;
    font-size: 12px;
    font-weight: 200;
    background: rgba(39, 43, 55, 0.8);
    border: 1px solid rgba(152, 163, 169, 1);
    color: #FFF000;
    opacity: .8;
    text-align: center;
    line-height: 22px;
    white-space: nowrap;

    
    &::before {
      content: "";
      position: absolute;
      left: 50%;
      top: 22px;
      transform: translate(-50%, 0);
      z-index: 3;
      border-top: 6px solid rgba(39, 43, 55, 0.8);
      border-right: 6px solid transparent;
      border-left: 6px solid transparent;
      box-sizing: content-box;
      width: 0;
      height: 0;
    }
    
    &::after {
      content: "";
      position: absolute;
      left: 50%;
      top: 23px;
      transform: translate(-50%, 0);
      z-index: 2;
      border-top: 6px solid rgba(152, 163, 169, 1);
      border-right: 6px solid transparent;
      border-left: 6px solid transparent;
      box-sizing: content-box;
      width: 0;
      height: 0;
    }
}

原理

小三角的实现知识点是border的运用,如下样式会得到这样的图形

border-top: 20px solid red;
border-right: 20px solid yellow;
border-bottom: 20px solid blue;
border-left: 20px solid green;

image.png