0

I don't know if this is possible or not, but any help would be very appreciated.

I have this code in my HTML:

<img src="mountains.jpeg" class="green inline-image" data-caption="A picture of mountains!">

where data-caption is a custom attribute.

I want to do something like this.

As you can see, the data-caption has to be in a small box right under the image, with the exact width as the image. I don't know if this is possible or not, so can you recommend an alternative way if not?

I tried doing something like this:

<img src="mountains.jpeg" class="green inline-image">
<div class="photo-caption">
    A picture of mountains!
</div>

CSS:

.inline-image {
    width:30%;
}

.photo-caption {
    width:30%;
    background-color:blue;
}

This works, but I'd prefer to not have to make a new <div> for every caption. I'd rather have it in the <img> tag.

Thank you very much!

Joe
  • 33
  • 2
  • 8

1 Answers1

2

Yeah it's possible using css content but problem in your case is you are using it on an img element which won't work on some browsers.

A different approach I would suggest is to insert your img element inside a div and have that custom attribute in there.

html:

<div class="img-block" data-caption="A picture of mountains!">
  <img src="mountains.jpeg" class="green inline-image" >
</div>

css

.img-block:after {
  content: attr(data-caption);
}

Reference

Robin Carlo Catacutan
  • 13,249
  • 11
  • 52
  • 85