我正在尝试在 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 asIMG
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/