html - CSS伪元素不起作用

标签 html css pseudo-element linear-gradients

我正在尝试在 div 内的图像下方创建渐变 border

我 100% 确定我的 CSS 代码本身是完美的,因为我之前已经在其他元素上测试过它。

问题是它以某种方式拒绝选择正确的元素并将伪元素放在它下面。

#profilePicture {
  width: 200px;
  margin-left: 25px;
  border-top: 1px solid #070707;
  border-left: 1px solid #070707;
  border-right: 1px solid #070707;
}
#pf {
  display: block;
  width: 200px;
}
#pf:first-child:after {
  content: '';
  position: absolute;
  width: 200px;
  height: 1px;
  background: -webkit-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: -moz-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: -o-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: linear-gradient(to right, #070707, #a1a1a1, #070707);
  top: -1px;
  left: 0;
}
<div id="profilePicture">
  <img id="pf" src="layout/images/profile/pf.png">
</div>

据我所知,它应该选择 #pf 这是其父元素的第一个子元素 (true) 并在其后添加伪元素?

编辑:我确实尝试过 top: 1px 和更大的 height 来确定。这没有效果。

最佳答案

您不能在 img 标签中使用伪元素(::before::after)(至少现在是这样)。

看什么W3C specs说:

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

因此您必须将伪元素应用于父元素。

您还需要在父元素中使用 position:relative,因为您在伪元素中应用 position:absolute。有了它,您将让伪元素与 DOM 保持一致。

请注意您的 CSS 有一些变化

body {
  margin: 0
}
#profilePicture {
  width: 200px;
  margin-left: 25px;
  position: relative;
  border: solid #070707;
  border-width: 1px 1px 0 1px
}
#pf {
  display: block;
}
#profilePicture::after {
  content: '';
  position: absolute;
  width: 200px;
  height: 5px;
  background: -webkit-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: -moz-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: -o-linear-gradient(left, #070707, #a1a1a1, #070707);
  background: linear-gradient(to right, #070707, #a1a1a1, #070707);
  bottom: 0;
  left: 0;
}
<div id="profilePicture">
  <img id="pf" src="//dummyimage.com/200x200&text=image">
</div>

关于html - CSS伪元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913384/

相关文章:

html - 为什么转换会破坏位置为 :fixed? 的元素的尺寸

html - 什么是::before 或::after 表达式,为什么它会显示在浏览器开发人员工具中?

html - CSS :active works incorrectly on a <a> element in IE9

html - 避免 :focus styles when clicking on div (only on tab key)

javascript - 在 Angular 2 中动态显示/隐藏菜单栏

javascript - 选择框 ID 值未在 javascript、html 中检索

html - 在 img 悬停时显示文本

html - 对齐单选按钮时出现 Flexbox 问题

html - 删除::after 选择器中的样式

javascript - 如何从顶部显示下拉菜单使用.show()