将绝对/相对定位与css伪元素一起使用

问题描述 投票:0回答:2

这里是CSS的新功能。我在下面有一个气泡,我希望span标签相对于divcontainer定位。如何在不影响伪元素显示的情况下这样做?

HTML(示例):

<div id = 'divcontainer'> 
  <span> </span>
</div>

CSS:

#divcontainer
{
    position: relative;
}
span
{
    position: relative;                /* I want the span tag to be positioned relative to the div.*/
    left: 18px;
    top: -15px;

    white-space: nowrap;
    font-size: 12px;
    background: white;
    border: 1px solid white;
    border-radius: 7px;
    padding-bottom: 5px;
    visibility: hidden;

}

span:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 45%;
    width: 0;
    height: 0;
    border: 18px solid transparent;
    border-top-color: white;
    border-bottom: 0;
    border-left: 0;
    margin-bottom: -10px;
}

任何人都非常感谢!

html css positioning pseudo-element
2个回答
0
投票

您应该对子元素应用绝对定位。

#divcontainer {
    position: relative;
}
span {
    position: absolute;             
    left: 18px;
    top: -15px;
}

如果元素的绝对值为positioning,则该元素的绝对位置为其第一个父元素。在您的情况下,#divcontainer是第一个定位的父级。


0
投票

您可以将position: absolute; both应用于子元素(spanand应用于其伪元素。两者的位置都相对于相对定位的父元素,因此也彼此相对。

© www.soinside.com 2019 - 2024. All rights reserved.