Div with CSS 内容,伪元素后不可见

Div with CSS content, after pseudo element is not visible

我有一个必须完成的 POC,我只能使用 CSS 来更新产品的样式。我已使用 CSS 内容属性将其中一张产品图片替换为徽标。

我必须添加一个带有 phone 数字的简单字符串,以显示在该徽标之后。我试图使用 :after 伪元素来做到这一点。这仅在 div 的内容为空(徽标已删除)时有效。

.demo {
  content: url('http://placehold.it/350x150')
}

.demo:after {
  content: 'test';
  display: inline-block;
}
<div class="demo"></div>

我已经尝试将 display 更改为 inline-block 并针对这两个规则对 heightwidth 进行硬编码。基本上我能找到的一切。任何帮助将不胜感激。

JSFiddle 在这里:https://jsfiddle.net/qykbjznm/

您可以替换 CSS 中的背景并将其作为图像放入 HTML:

.demo::after {
    content: 'test';
    display: inline-block;
}
<div class="demo">
  <img src='http://placehold.it/350x150'/>
</div>

或者甚至这样做:

.demo {
     background: url('http://placehold.it/350x150');
     height:150px;
     width:350px;
}

.demo::after {
    content: 'test';
}
<div class="demo"></div>

有两种不同的结果。

content 属性 替换元素内的所有内容。通过将 content 添加到非伪选择器,该内容将替换 ::before::after 伪选择器。

因此请尝试仅在 ::before::after 伪选择器中使用 content 属性。

.demo:before {
     content: url('http://placehold.it/350x150')
}

.demo:after {
    content: 'some text';
    display: block;
}
<div class="demo"></div>

我把你的 JSFiddle 弄乱了一点,我发现让 phone 数字显示在当前 div 下方的唯一真正方法是创建另一个 div:

<div class="demo"></div>
<div class="demo2"></div>
<style>
  .demo {
    content: url('http://placehold.it/350x150');
    height:150px;
    width:350px;
  }

  .demo2:before {
    content: "test";
  }
</style>

一些浏览器将 content 属性 应用于实际元素,尽管 not being supported in CSS2。 css-content-3 预计会允许这样做,但在 3 级规范成为标准之前,这实际上不会再发生几年(特别是考虑到它在过去 14 年),将 content 应用于实际元素应被视为非标准行为。

content的值属性是一张图片时,that image is inserted as replaced content。当它应用于实际元素时,这会阻止元素具有 ::before::after 伪元素。这就是为什么您的 ::after 伪元素没有出现的原因。

如前所述,您所要做的就是将图像应用于元素的 ::before 伪元素,而不是元素本身。