【问题标题】:Why is not possible to position '::after' pseudo-selector after an image? [duplicate]为什么不能在图像之后放置 '::after' 伪选择器? [复制]
【发布时间】:2020-11-25 01:25:12
【问题描述】:

假设我有这样的事情:

    .test-container {
        margin-left: 100px;
        margin-top: 40px;
    }

    .test-container::after {
        content: "";
        position: absolute;
        height: 2px;
        background-color: red;
        left: 0;
        right: 0;
    }
<div class="test-container">
   <h1>TESTE</h1>
   <h2>TESTE</h2>
   <img src="https://www.acmetek.com/wp-content/uploads/rapidssl-logo.png" />
</div>

可以看出::after 位于图像之前,而不是作为 div 的最后一个元素,但如果我在 div 内只有文本,::after 确实定位为最后一个元素。

我知道我可以将afterbottom 一起定位,并且我也知道我不能将伪选择器插入图像标签,但这里我使用的是div,但我没有得到这种行为。

我想知道它为什么会这样。

【问题讨论】:

  • 不要重复同一个问题,如果您不相信给出的答案,请编辑您的问题或要求澄清
  • 我添加了一份解释理论部分的副本
  • 我没有重复我的问题。您已经将此帖子添加到我所做的另一个问题中,它没有在那里回答我的问题,也没有在这里回答。
  • 确实如此,完全阅读以了解。这不是关于显示,而是关于静态位置。显示只会影响静态位置

标签: html css css-selectors pseudo-element


【解决方案1】:

你需要添加

display: block;

致您的::after

因为默认情况下,伪元素是inline 元素,img 标签也是inline。所以他们试图融入同一行。

一旦你创建了::afterdisplay: block,它就会自动适应下一行,并按预期停留在img标签的底部:

.test-container {
    margin-left: 100px;
    margin-top: 40px;
}

.test-container::after {
    content: "";
    display: block;
    position: absolute;
    height: 2px;
    background-color: red;
    left: 0;
    right: 0;
}
<div class="test-container">
   <h1>TESTE</h1>
   <h2>TESTE</h2>
   <img src="https://www.acmetek.com/wp-content/uploads/rapidssl-logo.png" />
</div>

【讨论】:

  • 现在说得通了。已经有几个小时它困扰着我了。非常感谢。
【解决方案2】:

我不知道为什么,但如前所述,&lt;img&gt;::after 伪元素都是内联元素。事实上,如果您使用普通的 &lt;span&gt; 而不是伪元素,您可以看到相同的行为。 (见下文)。

所以我不认为这是一个关于伪元素的问题,因为它是关于内联元素之间的交互,因为它们环绕一个绝对定位的元素。

不是一个完整的答案,但可能更接近一步。

    .test-container {
        margin-left: 100px;
        margin-top: 40px;
    }

    .test-container2 {
        content: "";
        position: absolute;
        height: 2px;
        background-color: red;
        left: 0;
        right: 0;
    }
<div class="test-container">
   <h1>TESTE</h1>
   <h2>TESTE</h2>
 

   <img src="https://www.acmetek.com/wp-content/uploads/rapidssl-logo.png" />
   <span class="test-container2"></span>
</div>

【讨论】:

  • I don't think this is as much a question about pseudoelements as it is about the interaction between the inline elements。你是对的,但这超出了我的知识范围。现在它是有道理的。非常感谢。
猜你喜欢
  • 2018-11-07
  • 1970-01-01
  • 2014-07-21
  • 2016-08-20
  • 2021-05-16
  • 1970-01-01
  • 2019-07-04
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多