P粉9261742882023-08-29 15:37:17
One way to do this is to create a ::before
pseudo-element above and next to the hovered text.
* { 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>
P粉9828815832023-08-29 00:55:51
There are many ways to do this, but if you just want the tooltip to be visible outside the container, you don't need to use z-index
or overflow
. You just need to move the tooltip into a positioning context inside the relative container.
Based on your comments, since you want the tooltip to only appear when hovering over the text, I would recommend that your relative container wrap exactly what you want to hover. To illustrate this, I added a border to the outer frame, compared to where you decide to use a relative container.
Then just change box:hover
to relative-container:hover
to target the correct element.
I tried to organize the HTML and class names to be more semantic and concise for illustration. Hope this helps!
.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>