position: relative 但兄弟姐妹认为该元素不存在

position: relative but siblings thinking the element doesn't exist

我正在创建工具提示。我的问题是,当工具提示出现时,兄弟姐妹会移动,这与 position: absolute 不同。我不能使用绝对位置,因为它使工具提示相对于浏览器 window 定位,而不是它的原始位置。

HTML

<p class="tooltip-anchor">Hover me</p>
<span class="tooltip">Hello!</span>

CSS

.tooltip-anchor:hover + .tooltip {
    display: inline-block;
}

.tooltip {
    display: none;
    position: relative;
    color: #fff;
    background: #333;
    padding: 0.25em;
}

我在代码笔上做了一个demo

对您的代码设置一些模式,您可以获得您想要的。 如果将跨度插入 p 标记,则可以将 position:absolute 设置为跨度(以及相对于它的容器的位置),然后根据需要修改它的位置。

Position absolute: The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.

<p style="font-size: 17px;">A simple tooltip. CSS is wonderful, may I say.</p>

<p class="tooltip-anchor">Hover me <span class="tooltip">Hello!</span></p>

<p>Hello</p>

CSS

body {
    font-family: sans-serif;
    font-size: 18px;
    text-align: center;
}

.tooltip-anchor{position:relative;display:inline-block;}/* modified */

.tooltip-anchor:hover  .tooltip {
    display: inline-block;
}

.tooltip {
    display: none;
    position: absolute;
    bottom: 20px;/* modified */
    left:-40px;/* modify for center */
    color: #fff;
    background: #333;
    padding: 0.25em;
    min-width: 150px;
    text-align: center;
}