纯css展示tooltip

作者: xusx 分类: Web 发布时间: 2022-04-27 18:25 浏览:270

效果

HTML/CSS tooltip

Hover Here to see the tooltip.

You can also hover here to see another example.

HTML

<h4>
  HTML/CSS tooltip
</h4>
<p>
  Hover <span class="tooltip" tooltip-data="Tooltip Content">Here</span> to see the tooltip.
</p>
<p>
  You can also hover <span class="tooltip" tooltip-data="This is another Tooltip Content">here</span> to see another example.
</p>

Style

.tooltip {
  position: relative;
  border-bottom: 1px dotted black;
}

.tooltip:before {
  content: attr(tooltip-data); 
  position: absolute;
  width: 250px;
  background-color: #efba93;
  color: #fff;
  text-align: center;
  padding: 15px;
  line-height: 1.1;
  border-radius: 5px;
  z-index: 1;
  opacity: 0;
  transition: opacity .5s;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  font-size: 0.70em;
  visibility: hidden;
}

.tooltip:after {
  content: "";
  position: absolute;
  bottom: 75%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  opacity: 0;
  transition: opacity .5s;
  border-color: #000 transparent transparent transparent;
  visibility: hidden;
}

.tooltip:hover:before, 
.tooltip:hover:after {
  opacity: 1;
  visibility: visible;
}

解析

  • 我们使用 tooltip class 去标志哪个元素需要展示 tooltip 信息。然后为该元素添加你喜欢的样式,这个方便演示,我们使用了 dotted border-bottom 的样式。
  • 接下来,我们创建一个 :before 伪元素,它将包含内容 content,指向特定的 attr()。这里指 attr(tooltip-data)
  • 接着,我们会创建一个 :hover 伪类,当用户鼠标移动道元素上时,它将设置 opacity1

此外,你可以包含自定义的样式。这取决于你设定的 tooltp 的数据,你也许需要调整其宽度或者边距。一旦你设定了 tooptip-data arrt() 类,你可以在你设计的其他部分应用。

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!