CSS锚点定位回退检测与tooltip效果实现实例页面

回到相关文章 »

效果:

我是提示内容

代码:

CSS代码:
.anchor {
  anchor-name: --my-anchor;
}

/* 提示浮层元素 */
.tooltip {
  position: fixed;
  margin-top: 1rem;
  position-anchor: --my-anchor;
  position-area: bottom;
  /* 垂直方向翻转 */
  position-try-fallbacks: flip-block; 
  /* 设置为锚点查询容器类型 */
  container-type: anchored;

  /* 向上小三角效果 */
  &::before {
    content: '';
    position: absolute;
    bottom: 100%; 
    inset-inline: 0;
    width: 1em;
    margin-inline: auto;
    aspect-ratio: 3/2;
    clip-path: polygon(50% 0, 100% 100%, 0% 100%);
    background: inherit;
  }
  background: #121212;
  color: #fff;
  padding: 4px 8px;
}

/* 如果触发了垂直翻转 */
@container anchored(fallback: flip-block) {
  .tooltip::before {
    /* 小三角翻转,定位调整 */
    scale: 1 -1;
    bottom: auto;
    top: 100%;
  }
}
HTML代码:
<span class="tooltip">我是提示内容</span>
<button class="anchor">我是按钮</button>