icecub icecub - 5 months ago 16
HTML Question

CSS pseudo class not working

I'm trying to create a gradient border underneath an image inside a div. I'm 100% sure that my CSS code itself is perfectly fine as I've tested it on other elements before. The problem is that somehow it refuses to select the correct element and place the pseudo element underneath it.



#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>





As far as I can tell it's supposed to select
#pf
which is the first child of its parent (true) and add the pseudo element after it?

Edit: I did try
top: 1px
and greater heights to be sure. This had no effect.

Answer

You can't use pseudo elements (::before and ::after) in img tag.

See what W3C specs says:

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.

So you have to apply the pseudo element to the parent instead.

Also you need to use position:relative in the parent because you are applying position:absolute in pseudo element to keep in the flow.

Note there is a few changes in your 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>