带有箭头

时间:2018-03-19 14:19:33

标签: css tooltip

我有这个:

span {
    padding: 10px;
    display: inline;
}

[title]:hover::before {
    background: #333;
    top: 20%;
    background: rgba(0,0,0,.8);
    border-radius: 5px;
    color: #fff;
    content: attr(title);
    padding: 5px 15px;
    position: absolute;
    z-index: 98;
    width: auto;
}
<span class="dijitButtonContents" id="saveButton" title="Save as draft"><span id="saveButton_label">Save</span></span>

我需要添加一个这样的指向箭头:

enter image description here

任何人都可以通过仅使用伪元素来帮助我实现这一目标吗?

感谢。

2 个答案:

答案 0 :(得分:2)

喜欢这个吗?

&#13;
&#13;
span {
  padding: 10px;
  display: inline;
}

[title] {
  position: relative;
}

[title]:hover:before {
  background: #333;
  top: 100%;
  background: rgba(0, 0, 0, .8);
  border-radius: 5px;
  color: #fff;
  content: attr(title);
  padding: 5px 15px;
  position: absolute;
  z-index: 98;
  width: auto;
  margin-top: 10px;
}

[title]:hover:after {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 10px solid #333;
  content: ' ';
  position: absolute;
  top: 100%;
  left: 50%;
}
&#13;
<span class="dijitButtonContents" id="saveButton" title="Save as draft"><span id="saveButton_label">Save</span></span>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我使用CSS三角形生成器来创建箭头。

修改:为中心对齐添加了CSS。还在CSS中提供了解释每个值的注释。

添加:hover伪选择器仅在悬停时显示工具提示。我删除了它们以便于开发。

.center-align {
  text-align: center;
}
[title] {
  position: relative;
}
[title]:before,
[title]:after {
  z-index: 98;
}

[title]:before {
  bottom: -10px;
  /* calculate 50% width of the parent element minus width of the current element */
  left: calc(50% - 10px);
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 10px 10px 10px;
  border-color: transparent transparent #333 transparent;
  content: "";
  position: absolute;
  display: block;
}

[title]:after {
  background: #333;
  /* calculate single line height plus height of the arrow element */
  top: calc(1em + 10px);
  border-radius: 5px;
  color: #fff;
  content: attr(title);
  padding: 5px 10px;
  position: absolute;
  /* calculate 50% width of the parent minus half of the width of current element minus half of the padding */
  left: calc(50% - 45px - 5px); 
  /* requires fixed width for calculation above */
  width: 90px;
  text-align: center;
}
<span class="dijitButtonContents" id="saveButton" title="Save as draft">  
  <span id="saveButton_label">Save and write a long description</span>
</span>
<br/><br/><br/><br/>
<span class="dijitButtonContents" id="saveButton" title="Save as draft">  
  <span id="saveButton_label">Save</span>
</span>

<div class="center-align">
  <span class="dijitButtonContents" id="saveButton" title="Save as draft">  
  <span id="saveButton_label">Save and write a long description</span>
  </span>
  <br/><br/><br/><br/>
  <span class="dijitButtonContents" id="saveButton" title="Save as draft">  
  <span id="saveButton_label">Save</span>
  </span>
</div>