【问题标题】:Using absolute/relative positioning with css pseudo elements使用 css 伪元素的绝对/相对定位
【发布时间】:2020-07-01 02:36:48
【问题描述】:

这里是 CSS 新手。使用 span 标签的对话气泡应相对于父 divcontainer 定位。

如何在不影响伪元素显示的情况下做到这一点?

HTML(示例):

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

CSS

#divcontainer  { position: relative; }

span  {
    /* span tag shall be positioned relative to the div.*/
    position: relative;                
    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


    【解决方案1】:

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

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

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

    【讨论】:

    • 伪元素也会受到影响吗?它会相对于 span 标签定位吗?谢谢!!
    【解决方案2】:

    您可以将position: absolute; both 应用到子元素 (span) 到它的伪元素。两者的位置将与相对定位的父元素相关,因此也相对于彼此。

    #divcontainer
    {
        position: relative;
        width: 200px;
        height: 200px;
        background: #ddd;
    }
    span
    {
        position: absolute;                
        left: 30px;
        top: 85px;
        white-space: nowrap;
        font-size: 12px;
        background: white;
        border: 1px solid white;
        border-radius: 7px;
        padding-bottom: 5px;
    
    }
    
    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: -15px;
    }
    <div id = 'divcontainer'> 
      <span>THE SPAN ELEMENT</span>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2017-03-09
      • 2019-06-22
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多