简体   繁体   中英

Elegantly annotate an image with the alt tag

I'd like to elegantly annotate an image on hover (or tap) with the contents of that image's alt tag. I'd like to use only CSS (if possible), and do not want to use jQuery because the page is incredibly simple and I don't want anything superfluous.

Whilst I can't write JS at the moment, I've only been able to find similar examples that use jQuery: display alt tag for image using this - jquery

Thank you.

Using the HTML5 <figure> element you can use the <figcaption> element to display the description of the image. It's a semantic approach to the thing you want to achieve. The alt attribute is for when the image can not be loaded and be different from the figcaption .

<figure>
  <img src="/random-image.jpg" alt="Alt description">
  <figcaption>Here comes the description</figcaption>
</figure>

You can hide the figcaption via CSS and on tap (or click) show it.

You can't use :before or :after as @Pointy correctly said. It's a self-closing element, so there is no content. Only attributes.

However, if you can control where the actual alt text goes, you could do something like this . Which makes use of the content/attr CSS property/combo. For details on this see David Walsh's post .

div {
    position:relative;
    width:500px;
    height:300px;
}

div:after {
    position:absolute;
    bottom:0;
    right:0;
    padding:10px;
    content:attr(data-alt);
    color:#FFF;
    background:#000;
}

Followed by HTML like this

<div data-alt="Sample Alt Text">
    <img src="//placeimg.com/500/300/any" />
</div>

Edit: if you want to page to validate, ensure you add an alt attribute to the img as well. Either empty alt="" , providing screen readers are able to read out the CSS content (I'm not 100% sure on this, probably depends on the screen reader). Or add the alt text in the alt attribute as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM