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!

7
  • stackoverflow.com/questions/18300536/… Commented May 17, 2015 at 14:57
  • You can use JavaScript ;-) Commented May 17, 2015 at 15:02
  • You can do it if you use div with background image Commented May 17, 2015 at 15:03
  • 1
    Maybe something like this jsfiddle.net/0gv5sv4q ? Commented May 17, 2015 at 15:04
  • 1
    Why the heck you want to do it in a wrong way? If you do not want to make "another" div, create figure and caption instead. Web documents are meant to be semantic Commented May 17, 2015 at 15:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.