<p>我想为这个元素制作一个自定义的工具提示,但是它被包含在一个框中,这个框没有足够的空间来显示工具提示,所以它只是被裁剪了(实际上我可以滚动来显示它,因为<code>overflow</code>被设置为<code>auto</code>,但是我希望它能够在不滚动的情况下可见)。有没有办法让它超出边界显示?我尝试过使用<code>z-index</code>但没有效果。</p>
<p>这就是我所说的:</p>
<p>
<pre class="brush:css;toolbar:false;">.box {
  width: 100px;
  height: 100px;
  overflow: auto;
  border-style: solid;
  border-color: red;
}
.tooltip {
  padding-top: 20px;
  position: relative;
  display: inline-block;
}
.tooltip .tooltiptext {
  display: none;
  max-width: 60vw;
  min-width: 15vw;
  background-color: white;
  border-style: solid;
  border-color: #1a7bd9;
  position: absolute;
  z-index: 1000000;
}
.tooltip:hover .tooltiptext {
  display: block;
}</pre>
<pre class="brush:html;toolbar:false;"><div class='box'>
  <div class='tooltip'> 鼠标悬停显示工具提示
    <div class='tooltiptext'>
      哇,这太棒了,这是一个史诗级的工具提示文本
    </div>
  </div>
</div></pre>
</p>
<p>编辑:重要的是悬停在元素上有效,而不是它所在的框上。</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
     
一种实现方法是创建一个位于被悬停文本上方和旁边的
::before伪元素。* { margin: 0; padding: 0; box-sizing: border-box; } .box { width: 100px; height: 100px; padding-top: 20px; border-style: solid; border-color: red; } .tooltip { position: relative; display: inline-block; } .tooltip::before { content: "哇,这太棒了,这是一个史诗般的工具提示文本"; position: absolute; left: 25%; bottom: -75%; display: none; width: 500px; background-color: white; border: 2px solid pink; } .tooltip:hover::before { display: flex; }<div class='box'> <div class='tooltip'> 鼠标悬停查看工具提示 </div> </div>有很多方法可以实现,但如果你只是想让工具提示在容器外可见,你不需要使用
z-index或overflow。你只需要将工具提示移动到相对容器内的定位上下文中。根据你的评论,由于你希望工具提示只在悬停在文本上时出现,我建议你的相对容器精确地包裹住你想悬停的内容。为了说明这一点,我在外框上添加了一个边框,与你决定使用相对容器的位置相比。
然后,只需将
box:hover更改为relative-container:hover以定位到正确的元素。我试图组织HTML和类名,使其更具语义性和简洁性以进行说明。希望对你有所帮助!
示例
.box { padding: 30px; border: blue solid; width: 300px; display: flex; align-items: center; } .relative-container { position: relative; } .box-content { border-style: solid; border-color: red; padding: 10px; } .tooltip { position: absolute; left: 0; top: 0; max-width: 60vw; min-width: 15vw; background-color: white; border: #1a7bd9 solid; display: none; } .relative-container:hover .tooltip { display: block; cursor: pointer; }<div class='box'> <div class='relative-container'> <div class='box-content'> Hover for tooltip. I have a little padding to give the text some room. </div> <div class='tooltip'> Wow, this is amazing, such an epic tooltip text. I'm aligned with the top of the box content containing text and take up the full width. I only appear when hovering over the box content (red outline), not the surrounding container (blue outline). </div> </div> </div>