0

I have an <img> over which I'd like to display a text overlay.

I'd like to display the text overlay at the bottom of the image - but I don't know the height of the image. (There are numerous images, all with the same standard width, but the width/height ratio differs from one image to the next.)

One approach is to use an absolutely positioned img::after:

main > figure {
display:inline-block;
position:relative;
width:400px;
height:284px;
background-color:rgb(0,0,127);
}

main > figure img {
display:block;
position:relative;
width:376px;
height:200px;
margin:12px auto;
background-color:rgb(255,255,0);
}

main > figure img::after {
content:'Example text overlay';
position:absolute;
display:block;
bottom:0;
left:0;
width:100%;
height:36px;
background-color:rgb(255,0,0);
}
<main>

<figure>
<img src="" alt="Image of variable height" />
</figure>

</main>

So far, so good.

But as soon as I add the image src. The ::after pseudo-element disappears:

main > figure {
display:inline-block;
position:relative;
width:400px;
height:284px;
background-color:rgb(0,0,127);
}

main > figure img {
display:block;
position:relative;
width:376px;
height:200px;
margin:12px auto;
background-color:rgb(255,255,0);
}

main > figure img::after {
content:'test';
position:absolute;
display:block;
bottom:0;
left:0;
width:36px;
height:36px;
background-color:rgb(255,0,0);
}
<main>

<figure>
<img src="http://placehold.it/376x200" alt="Image of variable height" />
</figure>

</main>

I assume the pseudo-element must be underneath the image file.

But how can I display it above the image file?

I've tried messing about with z-index to no avail.

No luck with opacity either.

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • Thanks @Paulie_D but the accepted answer you link to states: _"**:before** and **:after** only work with non-replaced elements."_ - as you can see in the first example above, `::after` is clearly working with `img`. You can see it working. – Rounin Feb 25 '16 at 10:52
  • 1
    Actually, I can't but if you search SO for "image overlay" I'm sure you'll find the right solution. Simply wrap the image in an `inline-block` div and use the pseudo-element on that. – Paulie_D Feb 25 '16 at 10:55
  • 1
    http://stackoverflow.com/questions/18322548/black-transparent-overlay-on-image-hover-with-only-css/18322705#18322705 – Paulie_D Feb 25 '16 at 10:57
  • Many thanks. Are you using Chrome? It's working in Firefox. I understand (from the comments below the accepted answer) that the issue is not is not so much that pseudo-elements don't work with replaced elements, but that the spec isn't yet fully-defined so implementation is (currently) left up to the browsers. – Rounin Feb 25 '16 at 11:02
  • 1
    FF does show it... ***but it shouldn't***. – Paulie_D Feb 25 '16 at 11:03

0 Answers0