CSS伪元素不起作用

时间:2016-06-20 00:57:35

标签: html css pseudo-element linear-gradients

我尝试在border内的图片下创建渐变div

我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>
&#13;
&#13;
&#13;

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

修改:我确实尝试了top: 1px和更高高度。这没有效果。

3 个答案:

答案 0 :(得分:4)

您无法在::before标记中使用伪元素(::afterimg)(至少目前为止)。

查看W3C specs说的内容:

  

请注意。此规范未完全定义:before:after与替换元素(例如HTML中的IMG)的交互。这将在未来的规范中更详细地定义。

所以你必须将伪元素应用于父元素。

此外,您需要在父级中使用position:relative,因为您在伪元素中应用了position:absolute。有了它,您将使用DOM将伪元素保留在流中。

请注意,CSS中有一些更改

&#13;
&#13;
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;
}
&#13;
<div id="profilePicture">
  <img id="pf" src="//dummyimage.com/200x200&text=image">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您不能将伪元素(:before:after)与img代码一起使用,在div附近创建额外img或添加:after转而使用#profilePicture元素。

此外,没有理由在first-child选择器中使用#pf:first-child:after,因为页面上只能有一个pf id的元素。

编辑:

  1. position: relative添加到您的#profilePicture
  2. top: 1px;
  3. 移除:after
  4. bottom: 0;添加到:after

答案 2 :(得分:0)

只需为此选择器position:relative添加#profilePicture,然后将#profilePicture::after更改为:

#profilePicture::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);
    bottom: 1px;
    left: 0;
}

相关问题